------------------------------------------------------------------------------
-- ADVANTAGE 2018.6.4.1000
-- IPay, SMS and minor fixes
-- 2018-05-15
------------------------------------------------------------------------------

--Prevent Logon From Incorrect App Version
UPDATE Sys_AW_Options
SET Control_Value = 1
WHERE Control_Name = 'chkLoginVersionError'
GO

UPDATE Sys_AW_Options
SET Control_Index = 0
WHERE Control_Name = 'chkHistoryDataSent' 
GO

--Insert i-PAY payment Type
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Payment_Methods
	WHERE [Description] = 'i-PAY'
) 
BEGIN
	INSERT Sys_AW_Payment_Methods
	(		
		[Description], 
		Sys_AW_Institution_Types_ID, 
		Slu_AW_Active_ID
	)
	VALUES
	(
		'i-PAY',
		2,
		1
	)
END
GO
UPDATE Sys_AW_Payment_Methods
SET Slu_AW_Active_ID = 2
Where Sys_AW_Payment_Methods_ID In (9)
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AB_GL_Transactions_Audit]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	CREATE TABLE AB_GL_Transactions_Audit
	(
		AB_GL_Transactions_Audit_ID	int IDENTITY(1,1) NOT NULL,
		Record_Action				varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		AB_GL_Transactions_ID		int NULL,
		Field						varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		Prev_Value					varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		New_Value					varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		Date_Captured				datetime NULL,
		[User_ID]					int NULL,
		 CONSTRAINT [PK_AB_GL_Transactions_Audit_ID] PRIMARY KEY CLUSTERED 
		(
			AB_GL_Transactions_Audit_ID ASC
		)
	)
END

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AB_GL_Transactions_Audit_AB_GL_Transactions_ID'
)
CREATE INDEX IX_AB_GL_Transactions_Audit_AB_GL_Transactions_ID
   ON AB_GL_Transactions_Audit (AB_GL_Transactions_ID)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AB_GL_Transactions_Audit_Date_Captured'
)
CREATE INDEX IX_AB_GL_Transactions_Audit_Date_Captured
   ON AB_GL_Transactions_Audit (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transaction_Payments_Date_Captured'
)
CREATE INDEX IX_AS_Transaction_Payments_Date_Captured
   ON AS_Transaction_Payments (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transactions_CBilling_Date_Captured'
)
CREATE INDEX IX_AS_Transactions_CBilling_Date_Captured
   ON AS_Transactions_CBilling (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AC_Assets_Date_Captured'
)
CREATE INDEX IX_AC_Assets_Date_Captured
   ON AC_Assets (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AO_Transactions_Date_Captured'
)
CREATE INDEX IX_AO_Transactions_Date_Captured
   ON AO_Transactions (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AP_Inventory_Adjustments_Date_Captured'
)
CREATE INDEX IX_AP_Inventory_Adjustments_Date_Captured
   ON AP_Inventory_Adjustments (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AB_GL_Transactions_Date_Captured'
)
CREATE INDEX IX_AB_GL_Transactions_Date_Captured
   ON AB_GL_Transactions (Date_Captured)
	WITH FILLFACTOR = 80
GO

--1. Add Cell_No
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='Cell_No'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD Cell_No Varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Cell_No]'
  -------------------------------------------------------
  
END
GO

--1. Add Email
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='Email'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD Email Varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Email]'
  -------------------------------------------------------
  
END
GO
--Insert SMS and I-Pay URL
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtSMS_URL'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtSMS_URL',
		0,
		'http://spiralsoft.co.za:85',
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtSMS_APPId'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtSMS_APPId',
		0,
		'f472bf58-68d7-437e-b732-fe247860ab53',
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtSMS_APIKey'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtSMS_APIKey',
		0,
		'BV3VWiS383e8BYfGQiSCjwflcCJqOuzoOt2NpSy8040=',
		Getdate(),
		1,
		1
	)
END
GO



IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtIPay_URL'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtIPay_URL',
		0,
		'I-Pay.co.za',
		Getdate(),
		1,
		1
	)
END
GO


IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtIPay_IsTest'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtIPay_IsTest',
		0,
		'False',
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtIPay_Pole'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtIPay_Pole',
		0,
		'30',
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtIPay_Expiry_Now'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtIPay_Expiry_Now',
		0,
		'20',
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtIPay_Expiry_Later'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtIPay_Expiry_Later',
		0,
		'90',
		Getdate(),
		1,
		1
	)
END
GO

--Insert chkHistoryDataSent - Used for Statistics
--chkHistoryDataSent
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkHistoryDataSent'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkHistoryDataSent',
		0,
		'',
		Getdate(),
		1,
		1
	)
END
GO

--POS Show SMS/E-Mail Screen
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_INV'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_INV',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_PF'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_PF',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_QT'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_QT',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_JC'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_JC',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

--Refund
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_REF'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_REF',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_SO'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_SO',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSMSEmail_CN'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSMSEmail_CN',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects 
				WHERE id = object_id(N'[dbo].[AS_Transaction_Payments_IPay]') 
				AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AS_Transaction_Payments_IPay](
		[AS_Transaction_Payments_IPay_ID] [int] IDENTITY(1,1) NOT NULL,
		[Ipay_Action] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[AS_Transactions_ID] [int] NULL,
		[AS_Transaction_Payments_ID] [int],
		[IPay_ID] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[IPay_Tran_Ref] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[IPay_Bank_Ref] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[IPay_URL]	[varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[IPay_Status] int NULL, --0 Still awaiting payment, 1 Paid, 2 Other
		[Amount] money NULL,
		[Cell_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[Email] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,	
		[Status_Code] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[Status_Description] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[HTTPStatus] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
	 CONSTRAINT [PK_AS_Transaction_Payments_IPay] PRIMARY KEY CLUSTERED 
	(
		[AS_Transaction_Payments_IPay_ID] ASC
	)
	) ON [PRIMARY]
END

	EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_One]', @objname = N'[dbo].[AS_Transaction_Payments_IPay].[Slu_AW_Active_ID]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_Companies]', @objname = N'[dbo].[AS_Transaction_Payments_IPay].[AW_User_Companies_ID]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[AS_Transaction_Payments_IPay].[Date_Captured]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_ID]', @objname = N'[dbo].[AS_Transaction_Payments_IPay].[User_ID]'
	GO
	
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transaction_Payments_IPay_AS_Transactions_ID'
)
DROP INDEX AS_Transaction_Payments_IPay.IX_AS_Transaction_Payments_IPay_AS_Transactions_ID
GO
CREATE INDEX IX_AS_Transaction_Payments_IPay_AS_Transactions_ID
   ON AS_Transaction_Payments_IPay (AS_Transactions_ID)
	WITH FILLFACTOR = 90
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transaction_Payments_IPay_IPay_Status'
)
DROP INDEX AS_Transaction_Payments_IPay.IX_AS_Transaction_Payments_IPay_IPay_Status
GO
CREATE INDEX IX_AS_Transaction_Payments_IPay_IPay_Status
   ON AS_Transaction_Payments_IPay (IPay_Status)
	WITH FILLFACTOR = 90
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transaction_Payments_IPay_AS_Transaction_Payments_ID'
)
DROP INDEX AS_Transaction_Payments_IPay.IX_AS_Transaction_Payments_IPay_AS_Transaction_Payments_ID
GO
CREATE INDEX IX_AS_Transaction_Payments_IPay_AS_Transaction_Payments_ID
   ON AS_Transaction_Payments_IPay (AS_Transaction_Payments_ID)
	WITH FILLFACTOR = 90
GO
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Tax_Codes
	WHERE [Description] LIKE '%14%'
)
BEGIN
	IF EXISTS
	(
		SELECT 1
		FROM Sys_AW_Tax_Codes
		WHERE Tax_Code = 'S'
		And Tax_Rate in (15)
	)
	BEGIN
		INSERT INTO Sys_AW_Tax_Codes ([Description], Tax_Code, Tax_Rate)
		VALUES('14% Not Registered', 'R', 14)

		INSERT INTO Sys_AW_Tax_Codes ([Description], Tax_Code, Tax_Rate)
		VALUES('14% Standard', 'P', 14)
	END
END
GO

IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AS_Payment_Unallocate]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	Create Table AS_Payment_Unallocate
	(AS_Payment_Unallocate_ID		Int Identity(1,1),
	 Note							Varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	 Date_Captured					Datetime)
END
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AO_Payment_Unallocate]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	Create Table AO_Payment_Unallocate
	(AO_Payment_Unallocate_ID	Int Identity(1,1),
	 Note							Varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	 Date_Captured					Datetime)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Bin_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Bin_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- sp_AP_Bin_Select 1, 555

-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Select
--Purpose       :Filters Products Bin Allocations
--Joins         :Tables: AP_Products
--Date          :2015-11-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Select]
	(
    	@CompanyID	int,
    	@ProductsID	int
	)

AS

SET NOCOUNT ON

	DECLARE @Include_Res_Stock_Validation	Varchar(5)
	
	SET @Include_Res_Stock_Validation = '1'
	
	SELECT @Include_Res_Stock_Validation = ISNULL(Control_Value,'0')
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkStockReservedJob'

	IF @Include_Res_Stock_Validation = '1'
	BEGIN
		SELECT 	b.[Description] AS [BIN],
				On_Hand - CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin(p.AP_Products_ID,p .Lup_AP_Product_Bins_ID)) AS [On_Hand],
				p.Lup_AP_Product_Bins_ID AS [ID]
		FROM AP_Products_Bins p
			INNER JOIN Lup_AP_Product_Bins b
				ON p.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE AP_Products_ID = @ProductsID
	END
	ELSE
	BEGIN
		SELECT 	b.[Description] AS [BIN],
				On_Hand AS [On_Hand],
				p.Lup_AP_Product_Bins_ID AS [ID]
		FROM AP_Products_Bins p
			INNER JOIN Lup_AP_Product_Bins b
				ON p.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE AP_Products_ID = @ProductsID
	END

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Products_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Products_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Products_Select
--Purpose       :NEW POS Product Search (Normal) Results for 3 ARGUMENTS max
--Functionality :Uses:    vw_AS_POS_Products    -- now REDUNDANT
--              :         vw_AS_POS_Products_Top_20_Perc
--              :         vw_AS_POS_Products_Gross_Contribution
--Date          :2002/02/16
--Authors       :TB
--MODS          :26/07/02 - Changed Previous search to WILDCARD(*) search and
--              :20/08/02 - Added new Search String ARGUMENTS: '+', '-', and '#'
--              :           '+' = by MARGIN DESCENDING     (GP Value: High to Low) 
--              :           '-' = by MARGIN ASCENDING      (GP Value: Low to High)
--              :           '#' = by Unit Price ASCENDING  (Price: Cheap to Expensive)
--              :           '%' = by GP% DESCENDING        (GP%: High to Low)
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :28/05/03 - Changed SORT ORDER for NORMAL search from [Description]
--              :           to [Qty on Hand] DESC, [Description]
--              :15/11/03 - Added KEYWORDS field as a search filter
--              :28/02/04 - Added [GrossProfit] SORT ORDER for MARGIN sorts (+ & -)
--              :19/03/04 - Top 20% by GP% now returned using '%' instead of nullstring
--              :19/03/04 - Modified Product Search to return ZERO rows if nullstring
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS in remaining views and
--              :           2. eliminated using vw_AS_POS_Products (the default search)
--              :           3. by moving its code to the top if this SP
--              :26/07/07 - Added p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID]
--              :29/07/07 - Added p.Standard_Cost as [Std Cost]
--              :09/08/07 - Removed unused [Job_Reserved] field
--              :26/08/07 - Added p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem]
--2004.3.8      :10/05/08 - Removed JOIN with Lup_AP_Product_Departments and its
--              :           Min_GP_Percentage field and renamed the alias of the
--              :           Max_Discount_Perc to [MinGPPerc] and the alias of the
--              :           Slu_AW_YesNo_Max_Discount_Perc to [UseMinGPPerc] (new Profit Protector)
--2004.3.9      :05/06/08 - Converted [Qty on Hand] to decimal(9, 3) (Sales Order formatting)
--              :05/06/08 - Added p.Pack_Mass AS [Pack Mass] (Sales Orders)
--              :16/06/08 - Removed unused [Price], [Date], [UserID], [Tax Code]
--              :16/06/08 - Rename [OpenOrderQty] to [On Order]
--2004.4.2      :24/10/08 - Added new field [Standard Margin]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--        ****  :02/09/10 - Added validation in WILDCARD search string: AND ISNUMERIC(@Filter1) > 0
--        ****  :02/09/10 - REMOVED WILDCARD search
--2004.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_POS_Products_Select]
    (    
        @CompanyID int,
        @Filter1 varchar(50) = '',
        @Filter2 varchar(50) = '',
        @Filter3 varchar(50) = ''
    )

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint
--             @Wildcard varchar(50),
--             @wc1 varchar(50),
--             @wc2 varchar(50)

--     SET @Wildcard = ''
--     SET @wc1 = ''
--     SET @wc2 = ''

	--DECLARE @Include_Res_Stock_Validation	Varchar(5)
	
	--SET @Include_Res_Stock_Validation = '1'
	
	--SELECT @Include_Res_Stock_Validation = ISNULL(Control_Value,'0')
	--FROM Sys_AW_Options
	--WHERE Control_Name = 'chkStockReservedJob'

	--IF @Include_Res_Stock_Validation = '1'
	--BEGIN



	DECLARE @POS_Products_Temp table
	(
		[Description] [varchar](50) NOT NULL,
		[Code] [varchar](20) NOT NULL,
		[Last Cost] [money] NULL,
		[Standard Discount] [int] NOT NULL,
		[Price 1] [money] NULL,
		[Promotion] [money] NULL,
		[Qty on Hand] [decimal](9, 3) NULL,
		[PromoProductID] [int] NULL,
		[Avg Cost] [money] NULL,
		[Gross Margin] [money] NULL,
		[Price 2] [money] NULL,
		[Unit Price] [money] NULL,
		[Qty] [decimal](9, 3) NULL,
		[Discount %] [int] NOT NULL,
		[Discount] [int] NOT NULL,
		[ID] [int] NOT NULL,
		[TypeID] [int] NULL,
		[Tax Rate] [decimal](5, 2) NULL,
		[Pack Mass] [decimal](9, 3) NULL,
		[Pack Volume] [decimal](9, 3) NULL,
		[On Hand] [decimal](9, 3) NULL,
		[Edit Price] [tinyint] NULL,
		[Edit Discount] [tinyint] NULL,
		[Keywords] [varchar](50) NULL,
		[GroupID] [smallint] NULL,
		[Reserved] [decimal](9, 3) NULL,
		[On Order] [decimal](9, 3) NULL,
		[CompanyID] [int] NOT NULL,
		[Active] [tinyint] NULL,
		[NonStockItem] [tinyint] NULL,
		[Average Margin] [money] NULL,
		[MinGPPerc] [decimal](5, 2) NOT NULL,
		[UseMinGPPerc] [tinyint] NULL,
		[GrossProfit] [money] NULL,
		[CostPlusGroupID] [smallint] NULL,
		[IsCostPlusItem] [tinyint] NULL,
		[Std Cost] [money] NULL,
		[Standard Margin] [money] NULL,
		[SKU_Code] [varchar](20) NULL,
		[Supercession] [varchar](20) NULL,
		[Alternate_Code1] [varchar](20) NULL,
		[Alternate_Code2] [varchar](20) NULL,
		[SellBelowCost] [tinyint] NULL,
		[ConsignmentStock] [decimal](9, 3) NULL,	
		UniqueID [int] IDENTITY(1,1) PRIMARY KEY		
	)
	
    -------------------------------------------------------------------------------
    SET @SearchType = 0

    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '+' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 1
        END

    ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '-' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 2
        END

	ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '#' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 3
        END

	ELSE
    IF (RIGHT(LTRIM(RTRIM(@Filter1)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter1))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter2)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter2))) > 1) OR
       (RIGHT(LTRIM(RTRIM(@Filter3)), 1) = '%' AND LEN(LTRIM(RTRIM(@Filter3))) > 1)
        BEGIN
            SET @SearchType = 4
        END

    ELSE
    IF LTRIM(RTRIM(@Filter1)) = ''        --> Returns an EMPTY rs
        BEGIN
            SET @SearchType = 5
        END

--     --> WILDCARD Pattern Matching using _ (underscore) character
--     IF LTRIM(RTRIM(@Filter1)) <> '' AND ISNUMERIC(@Filter1) > 0
--         BEGIN
--             SET @wc1 = REPLACE(LTRIM(RTRIM(@Filter1)), '/', '')
--             SET @wc2 = REPLACE(@wc1, '-', '')
--             IF LEN(@wc2) >= 5 AND ISNUMERIC(LEFT(@wc2, 3)) > 0
--                 BEGIN
--                     SET @Wildcard = 
--                         CASE LEN(@wc2)
--                              WHEN 5 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2)
--                              WHEN 6 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 1)
--                              WHEN 7 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '_' + RIGHT(@wc2, 2)
--                              WHEN 8 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '__' + RIGHT(@wc2, 2)
--                         END    
--                     SET @Wildcard = '%' + @Wildcard + '%'
--                 END
--         END

--> Normal Search BY DESCRIPTION ASCENDING (ANY ONE of the 3 arguments)
    IF @SearchType = 0
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  @Filter3 + '%'
					SET @Filter2 = '%' +  @Filter2 + '%'
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],                        
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                        ((p.Description like @Filter1 AND
--                          p.Description like @Wildcard OR
                          p.Description like @Filter2 AND
                          p.Description like @Filter3 ) OR 
                         (p.Product_Code like @Filter1 AND
                          p.Product_Code like @Filter2 AND
                          p.Product_Code like @Filter3) OR
                         (p.SKU_Code like @Filter1 AND
                          p.SKU_Code like @Filter2 AND
                          p.SKU_Code like @Filter3) OR
                         (p.Supercession like @Filter1 AND
                          p.Supercession like @Filter2 AND
                          p.Supercession like @Filter3) OR
                         (p.Alternate_Code1 like @Filter1 AND
                          p.Alternate_Code1 like @Filter2 AND
                          p.Alternate_Code1 like @Filter3) OR
                         (p.Alternate_Code2 like @Filter1 AND
                          p.Alternate_Code2 like @Filter2 AND
                          p.Alternate_Code2 like @Filter3) OR
                         (p.Keywords like @Filter1 AND
                          p.Keywords like @Filter2 AND
                          p.Keywords like @Filter3))
					ORDER BY [Qty on Hand] DESC, p.Description


				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  @Filter2 + '%'
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                        ((p.Description like @Filter1 AND
--                          p.Description like @Wildcard OR
                          p.Description like @Filter2) OR 
                         (p.Product_Code like @Filter1 AND
                          p.Product_Code like @Filter2) OR
                         (p.SKU_Code like @Filter1 AND
                          p.SKU_Code like @Filter2) OR
                         (p.Supercession like @Filter1 AND
                          p.Supercession like @Filter2) OR
                         (p.Alternate_Code1 like @Filter1 AND
                          p.Alternate_Code1 like @Filter2) OR
                         (p.Alternate_Code2 like @Filter1 AND
                          p.Alternate_Code2 like @Filter2) OR
                         (p.Keywords like @Filter1 AND
                          p.Keywords like @Filter2))
					ORDER BY [Qty on Hand] DESC, p.Description


				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  @Filter1 + '%'

                	SELECT 
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code], 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
                		p.Average_Cost AS [Avg Cost], 
                		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
                		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Qty],
                        0 as [Discount %],
                        0 as [Discount],
                		p.AP_Products_ID as [ID],
                		p.Lup_AP_Product_Types_ID as [TypeID],
                		tc.Tax_Rate as [Tax Rate], 
                		p.Pack_Mass AS [Pack Mass], 
                		p.Pack_Volume AS [Pack Volume], 
                		p.On_Hand AS [On Hand], 
                		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
                		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
                		p.Keywords as [Keywords],
                        p.Lup_AP_Discount_Groups_ID as [GroupID],
                        CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                        CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                        p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                        ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                        p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                        CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                        p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                        p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                		p.Standard_Cost AS [Std Cost],
                        CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
                	FROM AP_Products p  
                		LEFT JOIN Sys_AW_Tax_Codes tc
                            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
					WHERE p.AW_User_Companies_ID = @CompanyID AND 
                          p.Slu_AW_Active_ID = 1 AND
                         (p.Description like @Filter1 OR
--                          p.Description like @Wildcard OR
                          p.Product_Code like @Filter1 OR
                          p.SKU_Code like @Filter1 OR
                          p.Supercession like @Filter1 OR
                          p.Alternate_Code1 like @Filter1 OR
                          p.Alternate_Code2 like @Filter1 OR
                          p.Keywords like @Filter1)
					ORDER BY [Qty on Hand] DESC, p.Description

				END
		END


--> BY Gross Contibution DESCENDING (ANY ONE of the 3 arguments end with '+')
	ELSE
    IF @SearchType = 1
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] DESC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] DESC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] DESC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY Gross Contibution ASCENING (ANY ONE of the 3 arguments end with '-')
	ELSE
    IF @SearchType = 2
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [GrossProfit] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] ASC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [GrossProfit] ASC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [GrossProfit] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY Unit Price ASCENING (ANY ONE of the 3 arguments end with '#')
	ELSE
    IF @SearchType = 3
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Price 1] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Price 1] ASC

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [Price 1] ASC
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)                    				
					SELECT *
					FROM vw_AS_POS_Products_Gross_Contribution
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					ORDER BY [Price 1] ASC

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> BY GP% DESC (ANY ONE of the 3 arguments end with '%')
	ELSE
    IF @SearchType = 4
		BEGIN
			IF @Filter3 <> ''
				BEGIN
					SET @Filter3 = '%' +  LEFT(LTRIM(RTRIM(@Filter3)), (LEN(LTRIM(RTRIM(@Filter3))) - 1)) + '%'
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))
					ORDER BY [Gross Margin] DESC                          
					
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2 AND
                         [Description] like @Filter3 ) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2 AND
                          Code like @Filter3) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2 AND
                          SKU_Code like @Filter3) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2 AND
                          Supercession like @Filter3) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2 AND
                          Alternate_Code1 like @Filter3) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2 AND
                          Alternate_Code2 like @Filter3) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2 AND
                          Keywords like @Filter3))					                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter2 <>''
				BEGIN 
					SET @Filter2 = '%' +  LEFT(LTRIM(RTRIM(@Filter2)), (LEN(LTRIM(RTRIM(@Filter2))) - 1)) + '%'
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] > 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					ORDER BY [Gross Margin] DESC        
                          
					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND 
                          Active = 1 AND
                          [On Hand] <= 0 AND
                       (([Description] like @Filter1 AND
                         [Description] like @Filter2) OR 
                         (Code like @Filter1 AND
                          Code like @Filter2) OR
                         (SKU_Code like @Filter1 AND
                          SKU_Code like @Filter2) OR
                         (Supercession like @Filter1 AND
                          Supercession like @Filter2) OR
                         (Alternate_Code1 like @Filter1 AND
                          Alternate_Code1 like @Filter2) OR
                         (Alternate_Code2 like @Filter1 AND
                          Alternate_Code2 like @Filter2) OR
                         (Keywords like @Filter1 AND
                          Keywords like @Filter2))
					--ORDER BY [Qty on Hand] DESC, [Gross Margin] DESC					                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
			ELSE
			IF @Filter1 <> ''
				BEGIN
					SET @Filter1 = '%' +  LEFT(LTRIM(RTRIM(@Filter1)), (LEN(LTRIM(RTRIM(@Filter1))) - 1)) + '%'

					Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)					
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] > 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
                    ORDER BY [Gross Margin] DESC      
                          
                    Insert Into @POS_Products_Temp
					(
						[Description],[Code],[Last Cost],[Standard Discount],[Price 1],[Promotion],[Qty on Hand],[PromoProductID],
						[Avg Cost],[Gross Margin],[Price 2],[Unit Price],[Qty],[Discount %],[Discount],[ID],
						[TypeID],[Tax Rate],[Pack Mass],[Pack Volume],[On Hand],[Edit Price],[Edit Discount],[Keywords],
						[GroupID],[Reserved],[On Order],[CompanyID],[Active],[NonStockItem],[Average Margin],[MinGPPerc],
						[UseMinGPPerc],[GrossProfit],[CostPlusGroupID],[IsCostPlusItem],[Std Cost],[Standard Margin],
						[SKU_Code],[Supercession],[Alternate_Code1],[Alternate_Code2],[SellBelowCost], [ConsignmentStock]					
					)                    
					SELECT *
					FROM vw_AS_POS_Products
					WHERE CompanyID = @CompanyID AND
                          Active = 1 AND
                          [On Hand] <= 0 AND
                        ([Description] like @Filter1 OR
                          Code like @Filter1 OR
                          SKU_Code like @Filter1 OR
                          Supercession like @Filter1 OR
                          Alternate_Code1 like @Filter1 OR
                          Alternate_Code2 like @Filter1 OR
                          Keywords like @Filter1)
					--ORDER BY [Qty on Hand] DESC, [Gross Margin] DESC                          
					ORDER BY [Gross Margin] DESC
					
					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


--> Returns an EMPTY rs
    ELSE
    IF @SearchType = 5
        BEGIN
        	SELECT 
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.Last_Cost AS [Last Cost], 
                0 as [Standard Discount],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
        		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
        		p.Average_Cost AS [Avg Cost], 
        		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
        		p.Pack_Size AS [Qty],
                0 as [Discount %],
                0 as [Discount],
        		p.AP_Products_ID as [ID],
        		p.Lup_AP_Product_Types_ID as [TypeID],
        		tc.Tax_Rate as [Tax Rate], 
                p.Pack_Mass AS [Pack Mass], 
        		p.Pack_Volume AS [Pack Volume], 
        		p.On_Hand AS [On Hand], 
        		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
        		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
        		p.Keywords as [Keywords],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                p.AW_User_Companies_ID AS [CompanyID],
                p.Slu_AW_Active_ID AS [Active],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Standard_Cost AS [Std Cost],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 9
        END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_RPT_Invoice_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Invoice_Print
--Purpose       :POS Invoice printing
--Parameters    :
--Date          :2002/04/12
--Authors       :TB
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses from Physical to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :18/07/02 - Added Discount % per Line Item as [DetailDiscPerc]
--              :10/09/02 - Convert Discount % per Line from SMALLMONEY to MONEY
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :26/05/03 - Added ISNULL validation to customer address fields
--              :26/05/03 - Added Cell/Home/Work telephone number (next to Post Code)
--              :09/07/03 - Added Tax_Number (VATNo) effective 1 APR 2004 per SARS
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--              :09/02/04 - Added [JobSource] to print any JOBCARD source docs
--              :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :17/08/04 - Added p.Pack_Mass to aggregate invoice load mass
--              :21/12/04 - Added XREF to Sys_AW_Payment_Methods and PRINT
--              :08/01/05 - Added [JobRefNo] to print on new MAXIPREST layout
--              :02/02/05 - Added [TextMessage] to print on all invoice documents
--              :19/05/05 - Removed Payment Method from primary SELECT and pre-fetch
--2004.2.4      :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.1      :21/08/09 - Rearranged order of telephone numbers: Work/Cell/Home
--2004.3.2      :08/10/06 - Added [SerialNo] fields
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--              :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :05/07/08 - Renamed Job XRef from AS_Transaction_Sources
--              :           from 'Jobcard No: ' to 'Sales Order/Job No: '
--2004.4.5      :18/07/09 - Converted into DYNAMIC script to include NEW
--              :           POS Document Print Order of items settings
--2004.4.8      :17/04/10 - Reworked setting DEFAULT message and Added new QUOTE message
--2004.5.0      :26/01/11 - Added [Emails] for all customer e-mail addresses
--              :26/01/11 - Added [CompanyEmail] for company e-mail address
--2004.5.3      :18/07/11 - Added REPLACE syntax to REMOVE single APOSTROPHE in MESSAGES text
--2004.5.7 RGL  :2012-09-20 - Added check to to print tradeing name with company name
--2004.5.8 RGL  :2013-02-20 - Fixed check to to print tradeing name with customer and not company name
--RL	V6.0	:2014-01-28 - Use product print description instead of description
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.0	:2014-07-19 - Return TDHeader & TDDetail
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
--RL	V6.3	:2017-03-21 - Reworked Reg_No And Millage
--RL	V6.4	:2018-04-12 - Cell_No and EMail for document has been moved to AS_Transactions_Address_Detail table
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
    (
    	@TransactionID int
    )
AS

SET NOCOUNT ON

    DECLARE @SortOrder tinyint,
            @TranTypeID tinyint,
            @Message varchar(100),
            @DefaultMessage varchar(100),
            @QuoteMessage varchar(100),
            @PrintDefaultMessage varchar(10),
            @PrintQuoteMessage varchar(10),
            @OrderFilter tinyint,
            @sql varchar(8000)
            
	DECLARE @Customer_Name varchar(100),
 			@Inv_Address1 varchar(40),
 			@Inv_Address2 varchar(40),
 			@Inv_City varchar(30),
			@Inv_Code varchar(10),
			@Tax_Number varchar(16),
			@AW_YesNo_Invoice tinyint,
			
			@Delivery_Address varchar(40),
			@Delivery_Suburb varchar(40),
			@Delivery_City varchar(30),
			@Delivery_Post_Code varchar(10),
			@AW_YesNo_Delivery_Address tinyint,
			@AC_Customers_ID int,
			@IPay_Link varchar(100),
			@EMail varchar(100),
			@Cell_No varchar(100)
            
    --> Get TranTypeID
    SELECT @TranTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    --> Get POS Document Print Sort Order settings
    SELECT @SortOrder = ISNULL(Control_Value, 0)
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
    Control_Type = 'CheckBox' AND
    Control_Name = 'chkPOSPrintSortOrder'
    
    --> Get POS Document Print Sort Order Filter
    SELECT @OrderFilter = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
    Control_Name = 'optPOSSortOrderFilter' AND
    Control_Value = 'True'

    --------------------------------------------------------------------
    -- Set the MESSAGES text
    --------------------------------------------------------------------
    --> Get the DEFAULT Message text
    SELECT TOP 1 @DefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'

    --> Get the DEFAULT Message CheckBox setting
    SELECT TOP 1 @PrintDefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    --> Get the QUOTE Message text
    SELECT TOP 1 @QuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSQuoteText'

    --> Get the QUOTE Message CheckBox setting
    SELECT TOP 1 @PrintQuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSQuoteText'

    SET @Message = ''

    IF @TranTypeID = 1        --Quote message
        BEGIN
            IF @PrintQuoteMessage = '1' SET @Message = @QuoteMessage
        END
    ELSE                      --Default message
        BEGIN
            IF @PrintDefaultMessage = '1' SET @Message = @DefaultMessage
        END

    SET @Message = LEFT(@Message, 80)
        
    SET @AC_Customers_ID = 0
    SET @AW_YesNo_Invoice = 0
    SET @AW_YesNo_Delivery_Address = 0
    
    SELECT @AC_Customers_ID = AC_Customers_ID
    FROM AS_Transactions_Address a
	INNER JOIN AS_Transactions_Address_Detail d ON
		a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
	WHERE a.AS_Transactions_ID = @TransactionID

    IF @AC_Customers_ID <> 0
	BEGIN
		SELECT	@Customer_Name = REPLACE(ISNULL(Customer_Name, ''), '''', ''),
				@Inv_Address1 = REPLACE(ISNULL(Inv_Address1, ''), '''', ''),
				@Inv_Address2 = REPLACE(ISNULL(Inv_Address2, ''), '''', ''), 
				@Inv_City = REPLACE(ISNULL(Inv_City, ''), '''', ''),
				@Inv_Code = REPLACE(ISNULL(Inv_Code, ''), '''', ''),
				@Tax_Number = REPLACE(ISNULL(Tax_Number, ''), '''', ''),
				@AW_YesNo_Invoice = AW_YesNo_Invoice,
				@Delivery_Address = REPLACE(ISNULL(Delivery_Address, ''), '''', ''),
				@Delivery_Suburb = REPLACE(ISNULL(Delivery_Suburb, ''), '''', ''),
				@Delivery_City = REPLACE(ISNULL(Delivery_City, ''), '''', ''),
				@Delivery_Post_Code = REPLACE(ISNULL(Delivery_Post_Code, ''), '''', ''),
				@AW_YesNo_Delivery_Address = AW_YesNo_Delivery_Address,
				--V6.4 Added to Inv/Del Address
				@Cell_No = REPLACE(ISNULL(Cell_No, ''), '''', ''),
				@EMail = REPLACE(ISNULL(EMail, ''), '''', '')
		FROM AS_Transactions_Address a
		INNER JOIN AS_Transactions_Address_Detail d ON 
			a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
		WHERE a.AS_Transactions_ID = @TransactionID
	END    
	
	--V6.4 Added i-Pay link to show on Invoices
	IF @TranTypeID = 3
	BEGIN
		SELECT TOP 1 @IPay_Link = ISNULL(IPay_URL,'')
		FROM AS_Transaction_Payments_IPay
		WHERE AS_Transactions_ID = @TransactionID
		AND Ipay_Action IN ('PAY SUC','PAYDONE')
	END

	SELECT @IPay_Link = ISNULL(@IPay_Link,'')
	
    --------------------------------------------------------------------

	SET @sql = ' ' 
	SET @sql = @sql + ' DECLARE @WhichAddress tinyint, '
	SET @sql = @sql + ' @WhichName tinyint, '
	SET @sql = @sql + ' @PaymentMethod varchar(20) '

	SET @sql = @sql + ' SET @WhichAddress = 0 '

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SET @sql = @sql + ' SELECT @WhichAddress = ISNULL(Control_Index, 0) '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Type = ''OptionButton'' AND '
	SET @sql = @sql + ' Control_Name = ''optPOSPrintAddress'' AND '
	SET @sql = @sql + ' Control_Value = ''True'' '

	SET @sql = @sql + ' SELECT TOP 1 @WhichName = ISNULL(Control_Value, ''0'') '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Index = 0 AND '
	SET @sql = @sql + ' Control_Type = ''CheckBox'' AND '
	SET @sql = @sql + ' Control_Name = ''chkPOSPrintTradeName'' '

	SET @sql = @sql + ' SELECT TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''''), 20) '
	SET @sql = @sql + ' FROM AS_Transactions_Transactions att '
	SET @sql = @sql + ' LEFT JOIN AS_Transaction_Payments tp '
	SET @sql = @sql + ' ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID '
	SET @sql = @sql + ' LEFT JOIN Sys_AW_Payment_Methods pm '
	SET @sql = @sql + ' ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID '
	SET @sql = @sql + ' WHERE att.Source_AS_Transactions_ID = ' + CONVERT(varchar(20), @TransactionID)
	SET @sql = @sql + ' ORDER BY att.Source_AS_Transactions_ID '

    --------------------------------------------------------------------------------------------------
    --The query starts here
    --------------------------------------------------------------------------------------------------
	SET @sql = @sql + ' SELECT '

	IF @AW_YesNo_Invoice = 1
	BEGIN
      SET @sql = @sql + '''' + @Customer_Name + '''' + ' AS [CustomerName], '	  
	END
	ELSE
	BEGIN		
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
		SET @sql = @sql + ' THEN '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 	THEN '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	ELSE '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' ELSE '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' END AS [CustomerName], '
	END
	           	
    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
    --> POSTAL Address
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [PostOffice], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [PostCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [PostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [PostOffice], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [PostCity], '
		SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [PostCode], '
	END

	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [StreetAddress], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [StreetSuburb], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [StreetCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [StreetPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [StreetAddress], '
		SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [StreetSuburb], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [StreetCity], '
		SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [StreetPostCode], '
	END

	IF @AW_YesNo_Delivery_Address = 1
	BEGIN
		SET @sql = @sql + '''' + @Delivery_Address + '''' + ' AS [DeliverAddress], '      
		SET @sql = @sql + '''' + @Delivery_Suburb + '''' + ' AS [DeliverSuburb], '
		SET @sql = @sql + '''' + @Delivery_City + '''' + ' AS [DeliverCity], '
		SET @sql = @sql + '''' + @Delivery_Post_Code + '''' + ' AS [DeliverPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [DeliverAddress], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [DeliverSuburb], '
		SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [DeliverCity], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [DeliverPostCode], '
	END

	SET @sql = @sql + ' CONVERT(VARCHAR(12), c.AC_Customers_ID) AS [CustomerID], '
	SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') + ''('' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + '')'' AS [CustomerNo], '

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> '''' '
    SET @sql = @sql + ' THEN ''Merchant No: '' + RTRIM(LTRIM(c.Old_Customer_Number)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [MerchantNo], '

    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' tt.[Description] AS [TransactionType], '
    SET @sql = @sql + ' comp.Tax_Number AS [CompanyTaxNumber], '
    SET @sql = @sql + ' comp.E_Mail AS [CompanyEmail], '
    SET @sql = @sql + ' comp.Company_Name AS [CompanyName], '
--    SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
--    SET @sql = @sql + ' THEN comp.Company_Name + '' / '' + IsNull(comp.Company_Trading_Name,'''')'
--    SET @sql = @sql + ' ELSE comp.Company_Name '
--    SET @sql = @sql + ' END AS [CompanyName], '
    
    SET @sql = @sql + ' comp.Company_Trading_Name AS [TradingName], '
    SET @sql = @sql + ' comp.Company_Addr1 AS [CompanyAddress1], '
    SET @sql = @sql + ' comp.Company_Addr2 AS [CompanyAddress2], '
    SET @sql = @sql + ' comp.Company_City AS [CompanyCity], '
    SET @sql = @sql + ' comp.Company_Post_Code AS [CompanyPostCode], '
    SET @sql = @sql + ' comp.Company_Registration_Number AS [CompanyRegNo], '
    SET @sql = @sql + ' comp.Tel_No AS [CompanyTelNo], '
    SET @sql = @sql + ' comp.Fax_No AS [CompanyFaxNo], '
    SET @sql = @sql + ' comp.Delivery_Addr1 AS [Delivery_Addr1], '
    SET @sql = @sql + ' comp.Delivery_Addr2 AS [Delivery_Addr2], '
    SET @sql = @sql + ' comp.Delivery_Addr3 AS [Delivery_Addr3], '            
    SET @sql = @sql + ' rep.[Description] AS [RepName], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TransactionID], '
    SET @sql = @sql + ' t.Transaction_Number AS [TransactionNo], '
    SET @sql = @sql + ' CONVERT(varchar(12), t.Transaction_Date, 103) AS [TransactionDate], '
    SET @sql = @sql + ' t.Customer_Reference AS [TransactionCustomerRef], '
    SET @sql = @sql + ' t.Amount AS [TransactionAmount], '
    SET @sql = @sql + ' t.Total_Amount AS [TransactionTotalAmount], '
    SET @sql = @sql + ' t.Total_Discount_Amount AS [TransactionTotalDiscount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [TransactionTotalTax], '
    SET @sql = @sql + ' com.Comment AS [TransactionComment], '
-------------------------------------------------------------------------------
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '

--    SET @sql = @sql + ' p.Description AS [ProductDescription], '
    --RL 2014-01-28 Vs 6.0 Use print discription if there is a value instead of Description
    SET @sql = @sql + ' CASE WHEN LEN(ISNULL(Print_Description,'''')) > 0 '
    SET @sql = @sql + ' THEN p.Print_Description '
    SET @sql = @sql + ' ELSE p.Description '
    SET @sql = @sql + ' END AS [ProductDescription], '
    
    --V6.3 RL 2017/04/21 Added back order qty to display on Sales Order document
    SET @sql = @sql + ' (td.Quantity + td.Back_Order) AS [DetailQty], '    
    
    SET @sql = @sql + ' td.Unit_Price AS [DetailUnitPrice], '

    SET @sql = @sql + ' CASE WHEN (td.Unit_Price * (td.Quantity + td.Back_Order)) <> 0 '
    SET @sql = @sql + ' THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * (td.Quantity + td.Back_Order))) * 100), 2))) '
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END AS [DetailDiscPerc], '

    SET @sql = @sql + ' td.Discount_Amount AS [DetailDiscount] , '
    SET @sql = @sql + ' (td.Unit_Price * (td.Quantity + td.Back_Order)) + td.Discount_Amount AS [DetailAmount], '
    SET @sql = @sql + ' td.Tax_Amount AS [DetailTaxAmount], '
    SET @sql = @sql + ' td.Extended_Amount AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime], '
    SET @sql = @sql + ' u.UserName AS [UserCode], '
    SET @sql = @sql + ' t.Comment AS [Comment], '

  	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Cell_No + '''' + ' AS [TelNos], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '''') + '
		SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Cell_No)), '''') + '
		SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Home_Tel_No)), '''') AS [TelNos], '
	END
	--> TAX Number
    --SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Tax_Number + '''' + ' AS [VATNo], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	END

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> '''' '
    SET @sql = @sql + ' THEN ''Sales Order/Job No: '' + RTRIM(LTRIM(ts.Transaction_Numbers)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [JobSource], '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass], '
    SET @sql = @sql + ' @PaymentMethod AS [PayMethod], '

    SET @sql = @sql + ' CASE WHEN td.AS_Job_References_ID = 0 '
    SET @sql = @sql + ' THEN NULL '
    SET @sql = @sql + ' ELSE td.AS_Job_References_ID '
    SET @sql = @sql + ' END AS [JobRefNo], '

    SET @sql = @sql +  '''' + @Message + '''' + ' AS [TextMessage], '
    SET @sql = @sql + ' @WhichAddress AS [AddressType], '
    SET @sql = @sql + ' td.Serial_No AS [SerialNo], '
    SET @sql = @sql + ' td.Make AS [Make], '
    SET @sql = @sql + ' td.Customer AS [Customer], '
    SET @sql = @sql + ' @WhichName AS [NameType], '
    
  	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @EMail + '''' + ' AS [Emails], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Orders_URL)), '''') + '
		SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') + '
		SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') AS [Emails], '
	END
	    
    SET @sql = @sql + ' td.TDHeader AS [TDHeader], '
    SET @sql = @sql + ' td.TDDetail AS [TDDetail], '
	SET @sql = @sql + ' ISNULL(ca.Reg_No, '''') AS [Reg_No], '
	SET @sql = @sql + ' ISNULL(ca.Mileage, '''') AS [Mileage], '	
	--V6.4
	SET @sql = @sql + '''' + @IPay_Link + '''' + ' AS [IPay_Link] '

--	FROM vw_AS_Transactions t 
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + ' LEFT JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_User_Companies comp '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + ' ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Details td '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = td.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + ' ON td.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + ' ON t.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Sources ts '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = ts.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Comments com '
    SET @sql = @sql + ' ON t.AW_Comments_ID = com.AW_Comments_ID '
    SET @sql = @sql + ' LEFT JOIN AC_Assets ca '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = ca.AS_Transactions_ID '
    SET @sql = @sql + ' WHERE t.AS_Transactions_ID = ' + CONVERT(varchar(20), @TransactionID)

    IF @SortOrder = 1
        BEGIN
            IF @OrderFilter = 0        --Product Description
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Description '
                END
            ELSE
            IF @OrderFilter = 1        --Product Code
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Product_Code '
                END
            ELSE
            IF @OrderFilter = 2        --Product Type
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Types_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 3        --Product Group
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Groups_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 4        --Product Department
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Departments_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 5        --Product Location
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Locations_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 6        --Product Purchase Category
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Purchase_Categories_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 7        --Product Manufacturer
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Manufacturers_ID, p.Description '
                END
        END
    ELSE                    --Default
        BEGIN
            SET @sql = @sql + ' ORDER BY AS_Transaction_Details_ID '
        END

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_Sys_AC_Status_Get]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Sys_AC_Status_Get]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Stored Procedure



-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Get
--Purpose       :Get Sys_AC_Status
--Parameters    :
--Date          :2014-05-03
--Authors       :RL
--Version       :6.0
--MODS          :
--V6.4	RL		:2018-02-20 Add TDHeader and TDDetail to '#*D*# record
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Get]
AS

SET NOCOUNT ON


	DECLARE @DB								Varchar(256),
			@SpiralID						Int,
			@LastDayEND						DateTime,
			@DB_Ver							Varchar(30),
			@Company_Name					Varchar(50),
			@Company_Trading_Name			Varchar(50),
			@Company_Registration_Number	Varchar(16),
			@TAX_Number						Varchar(20),
			@Company_Addr1					Varchar(30),
			@Company_Addr2					Varchar(30),
			@Company_City					Varchar(20),
			@Company_Post_Code				Varchar(6),
			@Tel_No							Varchar(20),
			@Fax_No							Varchar(20),
			@E_Mail							Varchar(80),
			@Web_Home						Varchar(50),
			@Delivery_Addr1					Varchar(40),
			@Delivery_Addr2					Varchar(40),
			@Delivery_Addr3					Varchar(40),
			@Country						Varchar(50),
			
			@Today							DateTime,
    		@M1								Tinyint,
    		@Y1								Int,
    		@M2								Tinyint,
    		@Y2								Int,
    		@M3								Tinyint,
    		@Y3								Int,
    		@M4								Tinyint,
    		@Y4								Int,
    		@M5								Tinyint,
    		@Y5								Int,
    		@M6								Tinyint,
    		@Y6								Int,
    		@M7								Tinyint,
    		@Y7								Int,
    		@MinTransactionDate				DateTime,
    		@MaxTransactionDate				DateTime,
    		
			@chkCostSalesEditorGL_0			Varchar(10),
			@optZeroCostOverride_0			Varchar(10),
			@optZeroCostOverride_1			Varchar(10),
			@optZeroCostOverride_2			Varchar(10),
			@optInventoryValuation_0		Varchar(10),
			@optInventoryValuation_1		Varchar(10),
			@optInventoryValuation_2		Varchar(10),
			@chkUseStockAdjGL_0				Varchar(10),
			@chkUseProductPurchasesGL_0		Varchar(10),
			@chkUseProductSalesGL_0    		Varchar(10),
			@Network_Identity_Number    	Varchar(20),
			@Contact1_Email					Varchar(50),
			@Contact2_Email					Varchar(50),

			@chkHistoryDataSent				Integer,
			@txtCSalesExclusions			Varchar(250),
			@txtCSalesInclusions			Varchar(250),
			@txtCInsuranceFile				Varchar(250),

			@AS_CBilling_Providers_No		Integer,
			@AS_CBilling_Providers			Varchar(50),
			@chkSendConnectivitySales		Integer,
			@chkSendCBillingSales			Integer,
			@chkSendCInsuranceData			Integer,
			@chkSendCRewardsData			Integer,
			@txtNextCBFileNo				Varchar(50),
			@txtClickatellSMS				Varchar(50)
			
	DECLARE @Tbl Table
		(
			UniqueID [int] IDENTITY(1,1) PRIMARY KEY,		
			[Rec] [varchar](8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
		)
		
	SELECT @DB = DB_NAME()
	SELECT @Today = GETDATE()

	IF Exists	
	(
		SELECT 1
		FROM AS_Day_ENDs
	)
	BEGIN 
		SELECT @LastDayEND = MAX(Day_END) FROM AS_Day_ENDs
		SELECT @LastDayEND = DateAdd(d,-14,@LastDayEND)
	END
	ELSE
	BEGIN		
		SELECT @LastDayEND = '2016-01-01'
	END

	SET @chkHistoryDataSent = 0
	
	SELECT @chkHistoryDataSent = Control_Index
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkHistoryDataSent' 

	--Mark Stats Records
	UPDATE Sys_AC_Status
	SET Field12 = 1
	WHERE Field12 = 0

	--If this is the first time this procedure runs then select everything from 2016-01-01
	IF @chkHistoryDataSent = 0
	BEGIN
		SET @LastDayEND = '2016-01-01'

		--Mark Stats Records
		UPDATE Sys_AC_Status
		SET Field12 = 1
		WHERE Date_Captured >= @LastDayEND
	END
	
	--Get Ageing
	--@Y1,@M1
	SET @M1 = MONTH(@Today)

    SELECT @Y1 = Slu_AW_Years_ID
    FROM Slu_AW_Years
    WHERE [Description] = LTRIM(RTRIM(YEAR(@Today)))
	
	--Handeled On The Stats DB
	--SET @MinTransactionDate = '1900-01-01'
	--SELECT @MinTransactionDate = MIN(Transaction_Date)	
	--FROM AS_Transactions
	--WHERE Transaction_Date IS NOT NULL
	
	--SET @MaxTransactionDate = '1900-01-01'
	--SELECT @MaxTransactionDate = MAX(Transaction_Date)
	--FROM AS_Transactions
	--WHERE Transaction_Date IS NOT NULL

	--Sys_AW_Options
	SELECT @chkCostSalesEditorGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkCostSalesEditorGL'
	AND Control_Index = 0
	
	SELECT @optZeroCostOverride_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 0

	SELECT @optZeroCostOverride_1 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 1

	SELECT @optZeroCostOverride_2 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optZeroCostOverride'
	AND Control_Index = 2

	SELECT @optInventoryValuation_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 0

	SELECT @optInventoryValuation_1 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 1

	SELECT @optInventoryValuation_2 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'optInventoryValuation'
	AND Control_Index = 2

	SELECT @chkUseStockAdjGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseStockAdjGL'
	AND Control_Index = 0

	SELECT @chkUseProductPurchasesGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseProductPurchasesGL'
	AND Control_Index = 0

	SELECT @chkUseProductSalesGL_0 = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkUseProductSalesGL'
	AND Control_Index = 0

	SELECT @txtCSalesExclusions = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 0

	SELECT @txtCSalesInclusions = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 1

	Select @AS_CBilling_Providers_No = Control_Index From Sys_AW_Options Where Control_Name like 'optCBillingProvider' And Control_Value = 'True'

	SELECT @AS_CBilling_Providers = [Description] FROM Lup_AS_CBilling_Providers a WHERE @AS_CBilling_Providers_No =	(	
																															SELECT count(Lup_AS_CBilling_Providers_ID) 
																															FROM Lup_AS_CBilling_Providers b WHERE AW_User_Companies_ID = 1 AND
																															Slu_AW_Active_ID = 1 AND a.Lup_AS_CBilling_Providers_ID >= b.Lup_AS_CBilling_Providers_ID
																														)

	SELECT @chkSendConnectivitySales = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendConnectivitySales'

	SELECT @chkSendCBillingSales = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCBillingSales'

	SELECT @txtCInsuranceFile = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCInsuranceFile'

	SELECT @chkSendCInsuranceData = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCInsuranceData'

	SELECT @chkSendCRewardsData = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCRewardsData'

	SELECT @txtNextCBFileNo = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtNextCBFileNo'

	SELECT @txtClickatellSMS = ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 0

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 1

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 2

	SELECT @txtClickatellSMS = @txtClickatellSMS + '/' + ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtClickatellSMS'
	AND Control_Index = 3

	--@Y2,@M2	
    SET @M2 = @M1 - 1
    SET @Y2 = @Y1

    IF @M2 = 0
	BEGIN
		SET @M2 = 12
		SET @Y2 = @Y2 - 1
	END

	--@Y3,@M3	
    SET @M3 = @M2 - 1
    SET @Y3 = @Y2

    IF @M3 = 0
	BEGIN
		SET @M3 = 12
		SET @Y3 = @Y3 - 1
	END

	--@Y4,@M4	
    SET @M4 = @M3 - 1
    SET @Y4 = @Y3

    IF @M4 = 0
	BEGIN
		SET @M4 = 12
		SET @Y4 = @Y4 - 1
	END

	--@Y5,@M5	
    SET @M5 = @M4 - 1
    SET @Y5 = @Y4

    IF @M5 = 0
	BEGIN
		SET @M5 = 12
		SET @Y5 = @Y5 - 1
	END

	--@Y6,@M6	
    SET @M6 = @M5 - 1
    SET @Y6 = @Y5

    IF @M6 = 0
	BEGIN
		SET @M6 = 12
		SET @Y6 = @Y6 - 1
	END

	--@Y7,@M7	
    SET @M7 = @M6 - 1
    SET @Y7 = @Y6

    IF @M7 = 0
	BEGIN
		SET @M7 = 12
		SET @Y7 = @Y7 - 1
	END

	SELECT 
		@SpiralID = Sp_Account_ID,
		@Company_Name = Replace(IsNull(Company_Name,''),'~',''),
		@Company_Trading_Name = Replace(IsNull(Company_Trading_Name,''),'~',''),
		@Company_Registration_Number = Replace(IsNull(Company_Registration_Number,''),'~',''),
		@TAX_Number = Replace(IsNull(TAX_Number,''),'~',''),
		@Company_Addr1 = Replace(IsNull(Company_Addr1,''),'~',''),
		@Company_Addr2 = Replace(IsNull(Company_Addr2,''),'~',''),
		@Company_City = Replace(IsNull(Company_City,''),'~',''),
		@Company_Post_Code = Replace(IsNull(Company_Post_Code,''),'~',''),
		@Tel_No = Replace(IsNull(Tel_No,''),'~',''),
		@Fax_No = Replace(IsNull(Fax_No,''),'~',''),
		@E_Mail	= Replace(IsNull(E_Mail,''),'~',''),
		@Web_Home = Replace(IsNull(Web_Home,''),'~',''),
		@Delivery_Addr1 = Replace(IsNull(Delivery_Addr1,''),'~',''),
		@Delivery_Addr2	 = Replace(IsNull(Delivery_Addr2,''),'~',''),
		@Delivery_Addr3 = Replace(IsNull(Delivery_Addr3,''),'~',''),
		@Country = Replace(IsNull(s.[Description],''),'~',''),
		@Network_Identity_Number = Replace(IsNull(Network_Identity_Number,''),'~',''),
		@Contact1_Email = Replace(IsNull(Contact1_Email,''),'~',''),
		@Contact2_Email = Replace(IsNull(Contact2_Email,''),'~','')
	FROM AW_User_Companies c
		LEFT OUTER JOIN Slu_AW_Countries s
			ON c.Slu_AW_Countries_ID = s.Slu_AW_Countries_ID
	
	SELECT Top 1 @DB_Ver = Release FROM AA_Release Order By AA_Release_ID Desc

	--Insert Header Record		
	INSERT INTO @Tbl
	SELECT '#*H*#' + '~' + Convert(varchar(10),@SpiralID)  + '~' + @DB + '~' + @DB_Ver

	--Insert Sales Records
	INSERT INTO @Tbl
	SELECT
		'#*M*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(t.Transaction_Number,-9)) + '~' +									
		Convert(varchar(20),IsNull(t.Transaction_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(5),IsNull(t.Sys_AW_Transaction_Types_ID,255)) + '~' + 		
		Convert(varchar(20),IsNull(t.Total_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Tax_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Discount_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Total_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Payment_Amount,0)) + '~' + 
		Replace(IsNull(t.Customer_Reference,''),'~','') + '~' + 
		Replace(IsNull(t.Comment,''),'~','') + '~' + 		
		Convert(varchar(10),IsNull(t.[User_ID],-9)) + '~' +
		Replace(IsNull(u.FirstName,''),'~','') + ' ' + Replace(IsNull(u.Surname,''),'~','') + '~' +		--User_Full_Name					Varchar(100)
		Replace(IsNull(u.[UserName],''),'~','') + '~' +													--User_Name							Varchar(20)
		Convert(varchar(10),IsNull(t.Lup_AS_Reps_ID,-9)) + '~' +										--Transaction_Rep_ID				Int
		Case IsNull(tr.[Description],'')																
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(tr.[Description],''),'~','')
		END + '~' +																						--Transaction Rep					Varchar(30)
		Convert(varchar(10),IsNull(c.Lup_AS_Reps_ID,-9)) + '~' +										--Customer_Rep_ID					Int
		Case IsNull(cr.[Description],'')
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(cr.[Description],''),'~','')
		END + '~' +																						--Customer_Rep						Varchar(30)
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Types_ID,255)) + '~' + 
		Replace(IsNull(c.Surname,''),'~','') + '~' + 
		Replace(IsNull(c.Firstnames,''),'~','') + '~' + 
		Replace(IsNull(c.Initials,''),'~','') + '~' + 
		Replace(IsNull(c.IDReg_Number,''),'~','') + '~' + 
		Replace(IsNull(c.Customer_Number,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Box,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Office,''),'~','') + '~' + 
		Replace(IsNull(c.Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.Street_Address,''),'~','') + '~' + 
		Replace(IsNull(c.Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Street_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.City,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Address,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_City,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(c.Delivery_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(c.Head_Office,''),'~','') + '~' + 
		Replace(IsNull(ct.[Description],''),'~','') + '~' + 
		Replace(IsNull(c.Cell_No,''),'~','') + '~' + 
		Replace(IsNull(c.Home_Tel_No,''),'~','') + '~' + 
		Replace(IsNull(c.Work_Tel_No,''),'~','') + '~' + 
		Replace(IsNull(c.Fax_No,''),'~','') + '~' + 
		Replace(IsNull(c.Web_Site_URL,''),'~','') + '~' + 
		Replace(IsNull(c.Orders_URL,''),'~','') + '~' + 
		Replace(IsNull(c.Home_Email,''),'~','') + '~' + 
		Replace(IsNull(c.Work_Email,''),'~','') + '~' + 
		Replace(IsNull(c.Tax_Number,''),'~','') + '~' + 
		Replace(IsNull(cg.[Description],''),'~','') + '~' + 				
		Replace(IsNull(td.Inv_Address1,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_Address2,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_City,''),'~','') + '~' + 
		Replace(IsNull(td.Inv_Code,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Address,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Suburb,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_City,''),'~','') + '~' + 
		Replace(IsNull(td.Delivery_Post_Code,''),'~','') + '~' + 
		Replace(IsNull(td.Customer_Name,''),'~','') + '~' + 
		Replace(IsNull(td.Tax_Number,''),'~','') + '~' + 
		--Added V6.3
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Status_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(c.Credit_Limit,0)) + '~' + 
		Replace(IsNull(z.[Description],''),'~','') + '~' +												--Credit_Terms						Varchar(20)
		Convert(varchar(5),IsNull(z.Terms_Value,0)) + '~' +												--Credit_Terms_Value				Int
		Convert(varchar(5),IsNull(c.Sys_AC_Credit_Term_Types_ID,255)) + '~' +									
		Convert(varchar(5),IsNull(c.Sys_AC_Account_Types_ID,255)) + '~' + 
		Replace(IsNull(c.Credit_Insurers_Reference,''),'~','') + '~' +									--									Varchar(20)
		Convert(varchar(20),IsNull(c.Credit_Insurers_Limit,0)) + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Transaction_H	Int
		Convert(varchar(5),IsNull(c.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Customer			Int 
		Convert(varchar(20),ISNULL(t.Day_End,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' + 
		Convert(varchar(10),IsNull(t.AC_Customers_ID,-9)) + '~' +										--Product_Description				Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +									--Date_Extracted 
		'0'	+ '~' +																							--Transaction_Detail_Link			Int

		--V6.4
		--Erick 2018-04-13
		Replace(IsNull(td.Cell_No,''),'~','') + '~' +													--Cell_No	Varchar(16)
		Replace(IsNull(td.Email,''),'~','')																--Email		Varchar(100)
	FROM AS_Transactions t
		Left Join AC_Customers c
			On t.AC_Customers_ID = c.AC_Customers_ID
		Left Join Lup_AS_Reps tr
			On t.Lup_AS_Reps_ID = tr.Lup_AS_Reps_ID
		Left Join Lup_AS_Reps cr
			On c.Lup_AS_Reps_ID = cr.Lup_AS_Reps_ID
		Left Join AW_Users u
			On t.[User_ID] = u.AW_Users_ID		
		Left Join Sys_AC_Account_Types at
			On c.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
		Left Join Lup_AC_Customer_Types ct
			On c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID
		Left Join Lup_AC_Customer_Groups cg
			On c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID	
		Left Join AS_Transactions_Address ta
			On ta.AS_Transactions_ID = t.AS_Transactions_ID
		Left Join AS_Transactions_Address_Detail td
			On ta.AS_Transactions_Address_Detail_ID = td.AS_Transactions_Address_Detail_ID
		Left Join Slu_AW_Credit_Terms z
			On c.Slu_AW_Credit_Terms_ID = z.Slu_AW_Credit_Terms_ID
	WHERE
		t.Sys_AW_Transaction_Types_ID in (1,2,3,4,5,7,13,15,16,17,18,21,22,23,24,33,34,35,36)  AND
		t.Date_Captured > @LastDayEND

	INSERT INTO @Tbl
	SELECT
		'#*D*#'  + '~' + 
		Convert(varchar(10),IsNull(d.AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(d.AS_Transaction_Details_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(d.AP_Products_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(d.Quantity,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Unit_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Unit_Price,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Original_Price,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Original_Discount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Discount_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Tax_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Extended_Amount,0)) + '~' + 
		Convert(varchar(10),IsNull(d.AS_Job_References_ID,-9)) + '~' + 
		--V6.3
		Convert(varchar(5),IsNull(d.Slu_AW_Active_ID,255)) + '~' +										--Slu_AW_Active_ID_Transaction_D	Int 
		Convert(varchar(20),IsNull(d.Back_Order,0)) + '~' + 
		Convert(varchar(20),IsNull(d.Date_Captured,'1900-01-01'),120) + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +												--									Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +												--Product_Description				Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +									--Date_Extracted
		--V6.4
		Replace(IsNull(d.TDHeader,''),'~','') + '~' +													--TDHeader							Varchar(256)
		Replace(IsNull(d.TDDetail,''),'~','')															--TDDetail							Varchar(256)
	FROM AS_Transactions t
		Left Join AS_Transaction_Details d
			On t.AS_Transactions_ID = d.AS_Transactions_ID
		Left Join AP_Products p
			On d.AP_Products_ID = p.AP_Products_ID
	WHERE 
		t.Sys_AW_Transaction_Types_ID in (1,2,3,4,5,7,13,15,16,17,18,21,22,23,24,33,34,35,36)  AND
		t.Date_Captured > @LastDayEND
	
	--V6.3
	INSERT INTO @Tbl
	SELECT
		'#*Y*#'  + '~' + 
		Convert(varchar(10),IsNull(AS_Transaction_Payments_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(5),IsNull(Sys_AW_Payment_Methods_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)											--Date_Extracted
	FROM AS_Transaction_Payments
	WHERE Date_Captured > @LastDayEND

	--V6.4
	INSERT INTO @Tbl
	SELECT
		'#*I*#'  + '~' + 
		Convert(varchar(10),IsNull(AS_Transaction_Payments_IPay_ID,-9)) + '~' +							--Int
		Replace(IsNull(Ipay_Action,''),'~','') + '~' +													--Varchar(10)
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' +										--Int
		Convert(varchar(10),IsNull(AS_Transaction_Payments_ID,-9)) + '~' +								--Int
		Replace(IsNull(IPay_ID,''),'~','') + '~' +														--Varchar(50)
		Replace(IsNull(IPay_Tran_Ref,''),'~','') + '~' +												--Varchar(50)
		Replace(IsNull(IPay_Bank_Ref,''),'~','') + '~' +												--Varchar(50)
		Replace(IsNull(IPay_URL,''),'~','') + '~' +														--Varchar(250)
		Convert(varchar(10),IsNull(IPay_Status,-9)) + '~' +												--Int
		Replace(IsNull(Cell_No,''),'~','') + '~' +														--Varchar(20)
		Replace(IsNull(Email,''),'~','') + '~' +														--Varchar(100)
		Replace(IsNull(Status_Code,''),'~','') + '~' +													--Varchar(50)
		Replace(IsNull(Status_Description,''),'~','') + '~' +											--Varchar(250)
		Replace(IsNull(HTTPStatus,''),'~','') + '~' +													--Varchar(20)
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +								--Datetime
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' + 											--Date_Extracted
		
		--V6.4
		--Erick 2018-04-13
		Convert(varchar(20),IsNull(Amount,0))															--Amount		Decimal(18,3)
	FROM AS_Transaction_Payments_IPay
	WHERE Date_Captured > @LastDayEND

	--V6.3
	INSERT INTO @Tbl
	SELECT
		'#*X*#'  + '~' + 
		Convert(varchar(10),IsNull(AS_Transactions_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(Source_AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(Destination_AS_Transactions_ID,-9)) + '~' + 
		Convert(varchar(20),IsNull(Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)											--Date_Extracted		
	FROM AS_Transactions_Transactions
	WHERE Date_Captured > @LastDayEND

	--Centralised Sales
	INSERT INTO @Tbl
	SELECT
		'#*N*#'  + '~' +
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' +										--Integer
		Replace(IsNull(Customer_Number,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Network_Identity_Number,''),'~','') + '~' +										--Varchar(10)
		Convert(varchar(10),IsNull(Sys_AW_Transaction_Types_ID,255)) + '~' +							--Integer
		Replace(IsNull(Transaction_Number,''),'~','') + '~' +											--Varchar(19)
		Replace(IsNull(Original_Number,''),'~','') + '~' +												--Varchar(19)
		Convert(varchar(20),IsNull(Transaction_Date,'1900-01-01'),120) + '~' +							--Datetime
		Replace(IsNull(Manufacturer_Code,''),'~','') + '~' +											--Varchar(18)
		Convert(varchar(20),IsNull(Quantity,0)) + '~' +													--Decimal(18,3)
		Convert(varchar(20),IsNull(Extended_Amount,0)) + '~' +											--Decimal(18,3)
		Convert(varchar(20),IsNull(Tax_Amount,0)) + '~' +												--Decimal(18,3)
		Convert(varchar(20),IsNull(Discount_Amount,0)) + '~' +											--Decimal(18,3)
		Convert(varchar(10),IsNull(Lup_AP_Fail_Reasons_ID,255)) + '~' +									--Integer
		Convert(varchar(10),IsNull(Item_No,255)) + '~' +												--Integer
		Replace(IsNull(Authorization_No,''),'~','') + '~' +												--Varchar(30)
		Replace(IsNull(Registration_No,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Odometer_Reading,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Make,''),'~','') + '~' +															--Varchar(30)
		Replace(IsNull(Model,''),'~','') + '~' +														--Varchar(30)
		Replace(IsNull(Model_Year,''),'~','') + '~' +													--Varchar(10)
		Replace(IsNull(Client_ID_No,''),'~','') + '~' +													--Varchar(13)
		Replace(IsNull(Engine_No,''),'~','') + '~' +													--Varchar(24)
		Replace(IsNull(Chassis_No,''),'~','') + '~' +													--Varchar(24)
		Convert(varchar(10),IsNull(Lup_AP_Claim_Codes_ID,255)) + '~' +									--Integer
		Convert(varchar(20),IsNull(Xmit_Date,'1900-01-01'),120) + '~' +									--Datetime
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +								--Datetime
		Convert(varchar(10),IsNull(Slu_AW_Active_ID,255)) + '~' +										--Integer
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)											---Date_Extracted			Datetime
	From AS_Transactions_CBilling
	WHERE Date_Captured > @LastDayEND 

	--Insert Customer Asset Details
	INSERT INTO @Tbl
	SELECT
		'#*L*#'  + '~' +
		Convert(varchar(10),IsNull(AC_Customers_ID,-9)) + '~' +									--Integer
		Replace(IsNull(Make,''),'~','') + '~' +													--Varchar(30)
		Replace(IsNull(Model,''),'~','') + '~' +												--Varchar(30)
		Replace(IsNull(Model_Year,''),'~','') + '~' +											--Varchar(10)
		Convert(varchar(5),IsNull(Lup_AC_Asset_Types_ID,255)) + '~' +							--Integer
		Replace(IsNull(Reg_No,''),'~','') + '~' +												--Varchar(10)
		Replace(IsNull(Engine_No,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(Chassis_No,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(VIN_No,''),'~','') + '~' +												--Varchar(24)
		Replace(IsNull(Mileage,''),'~','') + '~' +												--Varchar(24)
		Replace(IsNull(Mileage_Date,''),'~','') + '~' +											--Varchar(10)
		Replace(IsNull(Tyre_Size,''),'~','') + '~' +											--Varchar(24)
		Replace(IsNull(Tyre_Qty,''),'~','') + '~' +												--Varchar(24)
		Convert(varchar(20),IsNull(Date_Captured,'1900-01-01'),120) + '~' +						--Datetime
		Convert(varchar(5),IsNull(Slu_AW_Active_ID,255)) + '~' +								--Integer
		Convert(varchar(10),IsNull(AS_Transactions_ID,-9)) + '~' +								--Integer
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120)									--Date_Extracted
	FROM AC_Assets
	WHERE Date_Captured > @LastDayEND

	--Insert Product Records
	INSERT INTO @Tbl
	SELECT
		'#*P*#'  + '~' + 
		Convert(varchar(10),IsNull(p.AP_Products_ID,-9)) + '~' + 
		Replace(IsNull(p.[Description],''),'~','') + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' + 
		Replace(IsNull(p.Manufacturer_Code,''),'~','') + '~' + 
		Replace(IsNull(m.[Description],''),'~','') + '~' + 
		Convert(varchar(20),IsNull(p.Last_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Average_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Standard_Cost,0)) + '~' + 
		Convert(varchar(20),IsNull(p.Price1_Effective_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(20),IsNull(p.Price1_Price1,0)) + '~' + 
		Convert(varchar(5),IsNull(p.Slu_AW_YesNo_Non_Stock_Item,255)) + '~' + 
		Convert(varchar(5),IsNull(p.Slu_AW_YesNo_Levy_Item,255)) + '~' + 
		Convert(varchar(20),IsNull(p.On_Hand,0)) + '~' + 
		--V6.3
		Replace(IsNull(t.[Description],''),'~','') + '~' +													--Product_Types						Varchar(50) 
		Replace(IsNull(g.[Description],''),'~','') + '~' +													--Product_Groups					Varchar(50)  
		Replace(IsNull(d.[Description],''),'~','') + '~' +													--Product_Departments				Varchar(50)  
		Replace(IsNull(l.[Description],''),'~','') + '~' +													--Product_Locations					Varchar(50)  
		Replace(IsNull(c.[Description],''),'~','') + '~' +													--Product_Purchase_Categories		Varchar(50)  
		Convert(varchar(5),IsNull(p.Slu_AW_Active_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(Last_Sale_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(20),IsNull(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0)) + '~' +		--Consignment_Supplier				Decimal(18,4)
		Convert(varchar(20),IsNull(dbo.fn_AP_Get_Products_Out_On_Consignment(p.AP_Products_ID),0)) + '~' +	--Consignment_Customer				Decimal(18,4)
		Convert(varchar(20),IsNull(p.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Replace(IsNull(p.Manufacturer_Description,''),'~','') + '~' +										--Manufacturer_Description			Varchar(50)
		Replace(IsNull(s.Supplier_Name,''),'~','') + '~' +													--Supplier Name						Varchar(50)
		Replace(IsNull(p.SKU_Code,''),'~','') + '~' +														--SKU_Code							Varchar(20)
		Replace(IsNull(p.Supercession,''),'~','') + '~' +													--Supercession						Varchar(20)
		Replace(IsNull(p.Alternate_Code1,''),'~','') + '~' +												--Alternate_Code1					Varchar(20)
		Replace(IsNull(p.Alternate_Code2,''),'~','') + '~' +												--Alternate_Code2					Varchar(20)
		Convert(varchar(5),IsNull(p.Sys_AW_Tax_Codes_ID,255)) + '~' +										--Sys_AW_Tax_Codes_ID				Integer
		Convert(varchar(20),IsNull(p.Min_Stock_Level,0)) + '~' +											--Min_Stock_Level					Varchar(20)
		Convert(varchar(20),IsNull(p.Service_Level,0)) + '~' +												--Service_Level						Decimal(18,3)
		Convert(varchar(20),IsNull(p.Max_Order_Qty,0)) + '~' +												--Max_Order_Qty						Decimal(18,3)
		Convert(varchar(20),IsNull(p.Min_Order_Qty,0))														--Min_Order_Qty						Decimal(18,3)
	FROM AP_Products p
		Left Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
		Left Join Lup_AP_Product_Types t
			On p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID	
		Left Join Lup_AP_Product_Groups g
			On p.Lup_AP_Product_Groups_ID = g.Lup_AP_Product_Groups_ID	
		Left Join Lup_AP_Product_Departments d
			On p.Lup_AP_Product_Departments_ID = d.Lup_AP_Product_Departments_ID	
		Left Join Lup_AP_Product_Locations l
			On p.Lup_AP_Product_Locations_ID = l.Lup_AP_Product_Locations_ID	
		Left Join Lup_AP_Purchase_Categories c
			On p.Lup_AP_Purchase_Categories_ID = c.Lup_AP_Purchase_Categories_ID
		Left Join AO_Suppliers s
			On p.Default_Supplier_ID = s.AO_Suppliers_ID

	--V6.3
	--Insert Supplier / GRV Info
	INSERT INTO @Tbl
	SELECT 
		'#*S*#'  + '~' +  
		Convert(varchar(10),IsNull(t.AO_Transactions_ID,-9)) + '~' +
		Convert(varchar(10),IsNull(t.AO_Suppliers_ID,-9)) + '~' +
		Replace(IsNull(s.Supplier_Name,''),'~','') + '~' +
		Replace(IsNull(c.[Description],''),'~','') + '~' +													--Credit_Terms					Varchar(20)
		Replace(IsNull(c.Terms_Value,''),'~','') + '~' +													--Credit_Terms_Value			Int
		Convert(varchar(20),IsNull(s.Credit_Limit,0)) + '~' +
		Convert(varchar(20),IsNull(t.Document_Date,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Convert(varchar(10),IsNull(t.AO_GRV_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(t.Trade_Discount_Total,0)) + '~' +										--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Rebate_Discount_Total,0)) + '~' +										--H_Rebate_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Other_Discount_Total,0)) + '~' +										--H_Other_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Net_Amount,0)) + '~' +													--H_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Tax_Amount,0)) + '~' +											--H_Total_Tax_Amount			Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Amount,0)) + '~' +												--H_Total_Amount				Decimal(18,4)
		Convert(varchar(20),IsNull(t.Payment_Amount,0)) + '~' +												--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Settlement_Discount,0)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +											--H_Slu_AW_Active_ID			Int
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +								--H_Date_Captured				Datetime		
		Convert(varchar(20),IsNull(g.Date_Received,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(d.AP_Products_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(d.Qty,0)) + '~' +
		Convert(varchar(20),IsNull(d.Unit_Price,0)) + '~' +
		Convert(varchar(20),IsNull(d.Trade_Discount_Amount,0)) + '~' +										--D_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Rebate_Discount_Amount,0)) + '~' +										--D_Rebate_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Other_Discount_Amount,0)) + '~' +										--D_Other_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Net_Amount,0)) + '~' +													--D_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Tax_Amount,0)) + '~' +													--D_Tax_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Total_Cost,0)) + '~' +													--D_Total_Cost					Decimal(18,4)
		Convert(varchar(5),IsNull(d.Slu_AW_Active_ID,255)) + '~' +											--D_Slu_AW_Active_ID			Int		
		Convert(varchar(20),IsNull(d.Date_Captured,'1900-01-01'),120) + '~' +								--D_Date_Captured				Datetime		
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
 		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted  
 		Replace(IsNull(m.[Description],''),'~','') + '~' +													--Product_Manufacturer			Varchar(50) 
		Replace(IsNull(y.[Description],''),'~','') + '~' +													--Product_Types					Varchar(50) 
		Replace(IsNull(r.[Description],''),'~','') + '~' +													--Product_Groups				Varchar(50)
		Convert(varchar(10),IsNull(d.AO_GRV_Details_ID,-9)) + '~' +  
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AO_Transactions t
		Inner Join AO_Suppliers s
			On t.AO_Suppliers_ID = s.AO_Suppliers_ID
		Inner Join Slu_AW_Credit_Terms c
			On s.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
		Left Outer Join AO_GRV g
			On t.AO_GRV_ID = g.AO_GRV_ID
		Left Outer Join AO_GRV_Details d
			On t.AO_GRV_ID = d.AO_GRV_ID
		Left Outer Join AP_Products p
			On p.AP_Products_ID = d.AP_Products_ID
		Left Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
		Left Join Lup_AP_Product_Types y
			On p.Lup_AP_Product_Types_ID = y.Lup_AP_Product_Types_ID	
		Left Join Lup_AP_Product_Groups r
			On p.Lup_AP_Product_Groups_ID = r.Lup_AP_Product_Groups_ID
	WHERE t.Date_Captured > @LastDayEND
	OR g.Date_Captured > @LastDayEND
	
	--V6.3
	--Product Adjustments
	INSERT INTO @Tbl
	SELECT 
		'#*A*#'  + '~' +
		Convert(varchar(10),IsNull(i.AP_Products_ID,-9)) + '~' +
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
		Convert(varchar(5),IsNull(Sys_AP_Adjustment_Types_ID,255)) + '~' +
		Convert(varchar(20),IsNull(Previous_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_On_Hand,0)) + '~' +
		Convert(varchar(20),IsNull(New_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_On_Hand,0)) + '~' +
		Replace(IsNull(Note,''),'~','') + '~' +																--								Varchar(70)
		Convert(varchar(20),IsNull(i.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(i.AP_Inventory_Adjustments_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted	
		Convert(varchar(10),IsNull(i.[User_ID],-9))															--User_ID						Int
	From AP_Inventory_Adjustments i
			Left Outer Join AP_Products p
				On p.AP_Products_ID = i.AP_Products_ID	
	WHERE i.Date_Captured > @LastDayEND
	
	--V6.3
	--GL Accounts Info
	INSERT INTO @Tbl
	SELECT 
		'#*G*#'  + '~' + 
 		Convert(varchar(10),IsNull(aa.AB_Accounts_ID,-9)) + '~' +
		Replace(IsNull(aa.[Description],''),'~','') + '~' +													--Account_Description			Varchar(50)
		Replace(IsNull(aa.Account_Number,''),'~','') + '~' +
		Replace(IsNull(ac.[Description],''),'~','') + '~' +													--Account_Categories			Varchar(100)
		Replace(IsNull(tc.[Description],''),'~','') + '~' +													--Tax_Codes						Varchar(50)
		Convert(varchar(18),IsNull(tc.Tax_Rate,0)) + '~' +													--								Char(1)
		Replace(IsNull(cc.[Description],''),'~','') + '~' +													--Account_Cost_Centers			Varchar(50)
		Convert(varchar(20),IsNull(aa.AB_Account_Balance,0)) + '~' +
		Convert(varchar(5),IsNull(aa.AW_YesNo_Controllable_ID,255)) + '~' +
		Convert(varchar(20),IsNull(aa.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(aa.Slu_AW_Active_ID,255)) + '~' +
		Replace(IsNull(ag.[Description],''),'~','') + '~' +													--Account_Groups				Varchar(50)
		Replace(IsNull(ad.[Description],''),'~','') + '~' +													--Account_Divisions				Varchar(50)
		Replace(IsNull(dp.[Description],''),'~','') + '~' +													--Account_Departments			Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted		
		Convert(varchar(5),IsNull(ca.Control_Number,255)) + '~' +											--Control_Number				Integer
		Replace(IsNull(ca.[Description],''),'~','') + '~' +													--Control_Account				Varchar(50)	
		Replace(IsNull(ca.[User_Description],''),'~','') + '~' +											--Control_Account_User			Varchar(50)	
		Convert(varchar(5),IsNull(ca.Control_Type,255))														--Control_Type					Integer
	FROM AB_Accounts aa
		Inner Join Sys_AB_Account_Categories ac
			On aa.Sys_AB_Account_Categories_ID = ac.Sys_AB_Account_Categories_ID
		Inner Join Sys_AW_Tax_Codes tc
			On aa.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
		Inner Join Lup_AB_Cost_Centers cc
			On aa.Lup_AB_Cost_Centers_ID = cc.Lup_AB_Cost_Centers_ID
		Inner Join Lup_AB_Account_Groups ag
			On aa.Lup_AB_Account_Groups_ID = ag.Lup_AB_Account_Groups_ID
		Inner Join Lup_AB_Account_Divisions ad
			On aa.Lup_AB_Account_Divisions_ID = ad.Lup_AB_Account_Divisions_ID
		Inner Join Lup_AB_Account_Departments dp
			On aa.Lup_AB_Account_Departments_ID = dp.Lup_AB_Account_Departments_ID

		Left Join AB_Control_Accounts ca
			On aa.AB_Accounts_ID = ca.AB_Accounts_ID

	--V6.3
	--Income & Balance Sheet Statement Setup
	INSERT INTO @Tbl
	SELECT
		'#*B*#'  + '~' +  
		'Sys_AB_B1' + '~' +																					--Statement_Level					Varchar(10)
		Convert(varchar(10),IsNull(Sys_AB_B1_ID,-9)) + '~' +												--Statement_ID						Integer
		Replace(IsNull([Description],''),'~','')															--Statement_Description				Varchar(100)
	FROM Sys_AB_B1
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_B2' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_B2_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_B2
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_B3' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_B3_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_B3
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I1' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I1_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I1
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I2' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I2_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I2
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I3' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I3_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I3
	UNION All
	SELECT
		'#*B*#'  + '~' +
		'Sys_AB_I4' + '~' +
		Convert(varchar(10),IsNull(Sys_AB_I4_ID,-9)) + '~' +
		Replace(IsNull([Description],''),'~','')
	FROM Sys_AB_I4
	ORDER BY 1
	
	--V6.3
	--Income & Balance Sheet Statement Setup
	INSERT INTO @Tbl
	SELECT
		'#*C*#'  + '~' + 
		Convert(varchar(10),IsNull(Sys_AB_Account_Categories_ID,-9)) + '~' +								--Sys_AB_Account_Categories_ID		Integer
		Replace(IsNull([Description],''),'~','') + '~' +													--Description						Varchar(100)
		Convert(varchar(10),IsNull(Sys_AB_B1_ID,-9)) + '~' +												--Sys_AB_B1_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_B2_ID,-9)) + '~' +												--Sys_AB_B2_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_B3_ID,-9)) + '~' +												--Sys_AB_B3_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I1_ID,-9)) + '~' +												--Sys_AB_I1_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I2_ID,-9)) + '~' +												--Sys_AB_I2_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I3_ID,-9)) + '~' +												--Sys_AB_I3_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_I4_ID,-9)) + '~' +												--Sys_AB_I4_ID						Integer
		Convert(varchar(10),IsNull(Sys_AB_Account_Types_ID,255)) + '~' +									--Sys_AB_Account_Types_ID			Integer
		Convert(varchar(18),IsNull(Notes,0))																--Notes								Decimal(5,2)
	FROM Sys_AB_Account_Categories

	--V6.3 Budgets
	INSERT INTO @Tbl
 	SELECT
 		'#*F*#'  + '~' + 
		Convert(varchar(10),IsNull(b.AB_Budgets_ID,-9)) + '~' + 
		Convert(varchar(10),IsNull(b.AB_Accounts_ID,-9)) + '~' +
		Replace(IsNull(a.[Description],''),'~','') + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Years_ID,255)) + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Months_ID,255)) + '~' + 
		Convert(varchar(20),IsNull(b.Budget_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(b.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(b.Slu_AW_Active_ID,255)) + '~' +		
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +
		
		Convert(varchar(5),IsNull(ca.Control_Number,255)) + '~' +											--Control_Number				Integer
		Replace(IsNull(ca.[Description],''),'~','') + '~' +													--Control_Account				Varchar(50)	
		Replace(IsNull(ca.[User_Description],''),'~','') + '~' +											--Control_Account_User			Varchar(50)	
		Convert(varchar(5),IsNull(ca.Control_Type,255))														--Control_Type					Integer
	FROM AB_Budgets b
		Inner Join AB_Accounts a
			On b.AB_Accounts_ID = a.AB_Accounts_ID
		Left Join AB_Control_Accounts ca
			On a.AB_Accounts_ID = ca.AB_Accounts_ID
	
	--V6.3 Transactions
	INSERT INTO @Tbl
 	SELECT
 		'#*T*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AB_GL_Transactions_ID,-9)) + '~' + 
		Replace(Replace(IsNull(t.[Description],''),'~',''), CHAR(13) + CHAR(10) , ', ' ) + '~' +			--GL_Description					Varchar(50)
		Convert(varchar(5),IsNull(t.Sys_AB_Transaction_Types_ID,255)) + '~' + 
		Convert(varchar(10),IsNull(t.AB_Accounts_ID,-9)) + '~' +  
		Replace(IsNull(a.[Description],''),'~','') + '~' +													--Account_Description				Varchar(50)
		Convert(varchar(20),IsNull(t.AB_Transaction_Date,'1900-01-01'),120) + '~' + 
		Replace(IsNull(t.AB_Source_Ref,''),'~','') + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +  
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Replace(IsNull(t.AB_Transaction_Ref,''),'~','') + '~' + 
		Convert(varchar(20),IsNull(t.AB_Transaction_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE t.Date_Captured > @LastDayEND
	
	INSERT INTO @Tbl
 	SELECT
 		'#*T*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AB_GL_Transactions_ID,-9)) + '~' + 
		Replace(Replace(IsNull(t.[Description],''),'~',''), CHAR(13) + CHAR(10) , ', ' ) + '~' +			--GL_Description					Varchar(50)
		Convert(varchar(5),IsNull(t.Sys_AB_Transaction_Types_ID,255)) + '~' + 
		Convert(varchar(10),IsNull(t.AB_Accounts_ID,-9)) + '~' +  
		Replace(IsNull(a.[Description],''),'~','') + '~' +													--Account_Description				Varchar(50)
		Convert(varchar(20),IsNull(t.AB_Transaction_Date,'1900-01-01'),120) + '~' + 
		Replace(IsNull(t.AB_Source_Ref,''),'~','') + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +  
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Replace(IsNull(t.AB_Transaction_Ref,''),'~','') + '~' + 
		Convert(varchar(20),IsNull(t.AB_Transaction_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		INNER JOIN AB_GL_Transactions_Audit x
			On t.AB_GL_Transactions_ID = x.AB_GL_Transactions_ID
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE x.Date_Captured > @LastDayEND

	--Customer Condensed Age Analysis
	SET FMTONLY ON
	Exec sp_AC_Customer_Statements_Temp_Insert @Today, 0, 0, 1, 1
	SET FMTONLY OFF
	
	--V6.3
	INSERT INTO @Tbl
    SELECT
		'#*W*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AC_Customers_ID,-9)) + '~' +
		Replace(IsNull(t.FullName,''),'~','') + '~' +														--								Varchar(100)
		Replace(IsNull(t.Customer_Number,''),'~','') + '~' +												--								Varchar(10)
		Convert(varchar(20),IsNull(t.Account_Balance, 0)) + '~' +
		Convert(varchar(20),IsNull(t.[Current],0)) + '~' +
		Convert(varchar(20),IsNull(t.[30Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[60Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[90Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[120Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[150Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[180+Days],0)) + '~' +
		Convert(varchar(20),IsNull(dbo.fn_AC_Get_Last_Payment_Date(t.AC_Customers_ID),'1900-01-01'),120) + '~' +--[Last_Pay_Date]				Datetime
		Convert(varchar(20),IsNull(dbo.fn_AC_Get_Last_Payment_Amount(t.AC_Customers_ID),0)) + '~' + 		--[Last_Pay_Amount]				Decimal(18,4)
		Convert(varchar(20),IsNull(c.Credit_Limit,0)) + '~' +
		Replace(IsNull(tt.[Description],''),'~','') + '~' +													--Credit_Terms					Varchar(20)
		Convert(varchar(10),IsNull(tt.Terms_Value,0)) + '~' +												--Credit_Terms_Value			Int
		Convert(varchar(5),IsNull(c.Sys_AC_Credit_Term_Types_ID,255)) + '~' +    
	    Convert(varchar(20),IsNull(c.Credit_Insurers_Limit,0)) + '~' +										--								Decimal(18,4)
	    Replace(IsNull(s.[Description],''),'~','') + '~' +													--Customer_Account_Status		Varchar(50)
	    Convert(varchar(18),IsNull(c.Default_Settlement_Discount,0)) + '~' +								--								Decimal(18,4)    
	    Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120)
	FROM AC_Statements_Temp t    
		INNER JOIN AC_Customers c 
			ON t.AC_Customers_ID = c.AC_Customers_ID
		LEFT JOIN Sys_AC_Account_Status s
			ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
		LEFT JOIN Slu_AW_Credit_Terms tt
			ON c.Slu_AW_Credit_Terms_ID = tt.Slu_AW_Credit_Terms_ID
				
	--Supplier Age Analysis
	SET FMTONLY ON
	EXEC sp_AO_Supplier_Remittances_Temp_Insert @Today, 1, 1, 0, @M1, @Y1, @M2, @Y2, @M3, @Y3, @M4, @Y4, @M5, @Y5, @M6, @Y6, @M7, @Y7
	SET FMTONLY Off
	
	--V6.3
	INSERT INTO @Tbl
    SELECT
		'#*K*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AO_Suppliers_ID,-9)) + '~' +
		Replace(IsNull(t.Supplier,''),'~','') + '~' +
		Convert(varchar(20),IsNull(t.Credit_Limit,0)) + '~' +
		Replace(IsNull(t.Credit_Terms,''),'~','') + '~' +
		Convert(varchar(20),IsNull(t.Default_Settlement_Discount,0)) + '~' +
		Convert(varchar(20),(  
								IsNull(t.[Current], 0) +
								IsNull(t.[30Days], 0) +
								IsNull(t.[60Days], 0) +
								IsNull(t.[90Days], 0) +
								IsNull(t.[120Days], 0) +
								IsNull(t.[150Days], 0) +
								IsNull(t.[180+Days], 0)
							)
				) + '~' +																					--Account_Balance				Decimal(18,4)
		Convert(varchar(20),IsNull(t.[Current],0)) + '~' +
		Convert(varchar(20),IsNull(t.[30Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[60Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[90Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[120Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[150Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.[180+Days],0)) + '~' +
		Convert(varchar(20),IsNull(t.To_Be_Paid_Total,0)) + '~' +
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120)
	FROM AO_Remittances_Temp t 
		LEFT JOIN AO_Suppliers s
			ON s.AO_Suppliers_ID = t.AO_Suppliers_ID
	WHERE (ISNULL(t.[Current], 0) +
		ISNULL(t.[30Days], 0) +
		ISNULL(t.[60Days], 0) +
		ISNULL(t.[90Days], 0) +
		ISNULL(t.[120Days], 0) +
		ISNULL(t.[150Days], 0) +
		ISNULL(t.[180+Days], 0)) <> 0
							
	--Insert Usage Records							
	INSERT INTO @Tbl
	SELECT 
		'#*U*#'  + '~' + 
		Convert(Varchar(10), Sys_AC_Status_ID) + '~' +  --ID
		[Field1] + '~' + 								--S ID		
		Replace([Field2],'~','') + '~' + 				--Server
		Replace([Field3],'~','') + '~' + 				--DB
		Replace([Field4],'~','') + '~' + 				--Computer Name
		Replace([Field5],'~','') + '~' + 				--App
		Replace([Field6],'~','') + '~' + 				--User
		Replace([Field7],'~','') + '~' + 				--Module
		Replace([Field8],'~','') + '~' + 				--Mac ADD
		Replace([Field9],'~','') + '~' + 				--Key
		Replace([Field10],'~','') + '~' + 				--App Ver And DB Ver
		Replace([Field11],'~','') + '~' + 				--SQL Ver
		Convert(Varchar(20), [Date_Captured], 120) 
	FROM
		Sys_AC_Status
	WHERE
		ISNULL(Field12,0) = 1

	--Insert Users						
	INSERT INTO @Tbl
	SELECT 
		'#*Q*#'  + '~' + 
		Convert(varchar(10),IsNull(u.AW_Users_ID,-9)) + '~' +										--AW_Users_ID			
		Replace(IsNull(u.UserName,''),'~','') + '~' +												--UserName					Varchar(20)
		Replace(IsNull(u.Password,''),'~','') + '~' +												--Password					Varchar(20)
		Replace(IsNull(u.Surname,''),'~','') + '~' +												--Surname					Varchar(40)
		Replace(IsNull(u.FirstName,''),'~','') + '~' +												--FirstName					Varchar(40)
		Replace(IsNull(u.User_Home_Tel_Number,''),'~','') + '~' +									--User_Home_Tel_Number		Varchar(16)
		Replace(IsNull(u.User_Cell_Number,''),'~','') + '~' +										--User_Cell_Number			Varchar(16)
		Replace(IsNull(u.User_Email,''),'~','') + '~' +												--User_Email				Varchar(50)
		Convert(varchar(20),IsNull(u.Activation_Date,'1900-01-01'),120) + '~' +						--Activation_Date			Datetime
		Convert(varchar(20),IsNull(u.Deactivation_Date,'1900-01-01'),120) + '~' +					--Deactivation_Date			Datetime

		Convert(varchar(5),IsNull(u.Sys_AW_Applications_ID,255)) + '~' +							--Sys_AW_Applications_ID	Int
		Convert(varchar(5),IsNull(u.IsCashier,255)) + '~' +											--IsCashier					Int
		Convert(varchar(5),IsNull(u.IsSupervisor,255)) + '~' +										--IsSupervisor				Int
		Convert(varchar(5),IsNull(u.IsDBAdmin,255)) + '~' +											--IsDBAdmin					Int
		Convert(varchar(5),IsNull(u.IsCRM,255)) + '~' +												--IsCRM						Int
		Convert(varchar(5),IsNull(u.IsController,255)) + '~' +										--IsController				Int
		Convert(varchar(5),IsNull(u.IsAccountant,255)) + '~' +										--IsAccountant				Int
		Convert(varchar(5),IsNull(u.IsDataExporter,255)) + '~' +									--IsDataExporter			Int
		Convert(varchar(5),IsNull(u.IsProcurementSupervisor,255)) + '~' +							--IsProcurementSupervisor	Int
		Convert(varchar(5),IsNull(u.Slu_AW_Active_ID,255)) + '~' +									--Slu_AW_Active_ID			Int
		Convert(varchar(5),IsNull(u.IsLevyController,255)) + '~' +									--IsLevyController			Int
		Convert(varchar(5),IsNull(u.IsRecordsManager,255)) + '~' +									--IsRecordsManager			Int
		Convert(varchar(5),IsNull(u.IsBinSuper,255)) + '~' +										--IsBinSuper				Int
		Convert(varchar(5),IsNull(u.IsTillPayout,255)) + '~' +										--IsTillPayout				Int
		Convert(varchar(10),IsNull(u.[User_ID],-9)) + '~' +											--User_ID					Int
		Replace(IsNull(u.Lup_AP_Product_Bins_ID,''),'~','') + '~' +									--Lup_AP_Product_Bins_ID	Int
		Replace(IsNull([Description],''),'~','') + '~' +											--Bin						Varchar(50)
		Convert(Varchar(20), u.Date_Captured, 120)													--Date_Captured				Datetime
	FROM
		AW_Users u
			Left Join Lup_AP_Product_Bins b
				ON u.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID

	--Insert Usage Records							
	INSERT INTO @Tbl
	SELECT 
		DISTINCT
		'#*Z*#'  + '~' + 		
		Convert(Varchar(5),@SpiralID) + '~' +
		@Company_Name + '~' +
		@Company_Trading_Name + '~' +
		@Company_Registration_Number + '~' +
		@TAX_Number + '~' +
		@Country + '~' +
		@Company_Addr1 + '~' +
		@Company_Addr2 + '~' +
		@Company_City + '~' +
		@Company_Post_Code + '~' +
		@Tel_No + '~' +
		@Fax_No + '~' +
		@E_Mail + '~' +
		@Web_Home + '~' +
		@Delivery_Addr1 + '~' +
		@Delivery_Addr2 + '~' +
		@Delivery_Addr3 + '~' +
		
		--Convert(Varchar(20), @MinTransactionDate, 120) + '~' +											--Min Transaction Date  
		--Convert(Varchar(20), @MaxTransactionDate, 120) + '~' +											--Max Transaction Date
		'' + '~' +																							--Min Transaction Date  
		'' + '~' +																							--Max Transaction Date
		Convert(varchar(10),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted
		Convert(varchar(10),IsNull(@chkCostSalesEditorGL_0,-9)) + '~' +										--chkCostSalesEditorGL_0		Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_0,-9)) + '~' +										--optZeroCostOverride_0			Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_1,-9)) + '~' +										--optZeroCostOverride_1			Varchar(10)
		Convert(varchar(10),IsNull(@optZeroCostOverride_2,-9)) + '~' +										--optZeroCostOverride_2			Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_0,-9)) + '~' +									--optInventoryValuation_0		Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_1,-9)) + '~' +									--optInventoryValuation_1		Varchar(10),
		Convert(varchar(10),IsNull(@optInventoryValuation_2,-9)) + '~' +									--optInventoryValuation_2		Varchar(10),
		Convert(varchar(10),IsNull(@chkUseStockAdjGL_0,-9)) + '~' +											--chkUseStockAdjGL_0			Varchar(10),
		Convert(varchar(10),IsNull(@chkUseProductPurchasesGL_0,-9)) + '~' +									--chkUseProductPurchasesGL_0	Varchar(10),
		Convert(varchar(10),IsNull(@chkUseProductSalesGL_0,-9)) + '~' +										--chkUseProductSalesGL_0		Varchar(10)		
		@Network_Identity_Number + '~' +																	--Network_Identity_Number		Varchar(20)
		@Contact1_Email + '~' +																				--Contact1_Email				Varchar(50)
		@Contact2_Email + '~' + 																			--Contact2_Email				Varchar(50)	
		Convert(varchar(10),IsNull(@chkHistoryDataSent,-9)) + '~' +											--chkHistoryDataSent			Integer
		Replace(IsNull(@txtCSalesExclusions,''),'~','') + '~' +												--txtCSalesExclusions			Varchar(250)	
		Replace(IsNull(@txtCSalesInclusions,''),'~','') + '~' +												--txtCSalesInclusions			Varchar(250)
		Replace(IsNull(@txtCInsuranceFile,''),'~','') + '~' +												--txtCInsuranceFile				Varchar(250)
		Replace(IsNull(@AS_CBilling_Providers,''),'~','') + '~' +											--AS_CBilling_Providers			Varchar(50)
		Convert(varchar(10),IsNull(@chkSendConnectivitySales,-9)) + '~' +									--chkSendConnectivitySales		Integer
		Convert(varchar(10),IsNull(@chkSendCBillingSales,-9)) + '~' +										--chkSendCBillingSales			Integer
		Convert(varchar(10),IsNull(@chkSendCInsuranceData,-9)) + '~' +										--chkSendCInsuranceData			Integer
		Convert(varchar(10),IsNull(@chkSendCRewardsData,-9)) + '~' +										--chkSendCRewardsData			Integer
		Replace(IsNull(@txtNextCBFileNo,''),'~','') + '~' +													--txtNextCBFileNo				Varchar(50)
		Replace(IsNull(@txtClickatellSMS,''),'~','')														--txtClickatellSMS				Varchar(50)
	FROM
		Sys_AC_Status
	WHERE
		ISNULL(Field12,0) = 1

	IF @chkHistoryDataSent = 0
	BEGIN
		UPDATE Sys_AW_Options
		SET Control_Index = 1
		WHERE Control_Name = 'chkHistoryDataSent' 
	END

	SELECT Rec FROM @Tbl ORDER BY UniqueID

SET NOCOUNT OFF

GO



IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Insert_OR_Update_Product_Suppliers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Insert_OR_Update_Product_Suppliers]
GO
-----------------------------------------------------------------------------
--Description   :sp_AP_Insert_OR_Update_Product_Suppliers
--Purpose       :Used to link a Product to a Supplier
--Functionality :
--Parameters    :
--Date          :2002/03/22
--Authors       :TB
--Version       :1.0.0
--MODS          :06/10/02 - Added @Choice selection and new UNLINK choice
--              :04/10/03 - Added NEW Trade_Disc_Perc for Nett Billing and
--              :           NEW Inventory Manager's Discount column
--              :04/10/03 - Added NEW Trade_Disc_Date for NEW Discount above
--V6.3	RL	2017-09-07	:Update products default supplier if it currently set to ID 1 (<None>)
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_OR_Update_Product_Suppliers]
    (
    	@Choice tinyint ,
    	@Product_ID int,
    	@Supplier_ID int,
        @TradeDiscPerc decimal(5,2),
        @TradeDiscDate datetime,
    	@Lead_Time smallint ,
    	@StartDate datetime,
    	@Trade_Disc_Formula_ID smallint ,
    	@Rebate_Disc_Formula_ID smallint ,
    	@User_ID int,
        @Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @New_ID int
	SET @New_ID = 0
	
    IF @Choice = 0    --Link Supplier
        BEGIN
            IF NOT EXISTS
                (
                    SELECT AP_Products_Suppliers_ID
                    FROM AP_Products_Suppliers
                    WHERE AP_Products_ID = @Product_ID AND
                          AO_Suppliers_ID = @Supplier_ID AND
                          AW_User_Companies_ID = @Company_ID
                )
        		BEGIN 
                    INSERT INTO AP_Products_Suppliers
                        (
            				AP_Products_ID,
            				AO_Suppliers_ID,
                            Trade_Disc_Perc,
                            Trade_Disc_Date,
            				Lead_Time,
            				Start_Date,
            				AW_Trade_Discount_Formula_ID,
            				AW_Rebate_Discount_Formula_ID,
            				Date_Captured,
            				[User_ID],
            				AW_User_Companies_ID,
            				Slu_AW_Active_ID
                        )
        			VALUES
                        (
                            @Product_ID,
                            @Supplier_ID,
                            @TradeDiscPerc,
                            @TradeDiscDate,
                            @Lead_Time,
                            @StartDate,
                            @Trade_Disc_Formula_ID,
                            @Rebate_Disc_Formula_ID,
                            Getdate(),
                            @User_ID,
                            @Company_ID,
                            1
                        )
        
        			SELECT @New_ID = Scope_Identity()

					--RL V6.3 Updates Products default supplier only if it currently set to <None>. 
					--Supplier ID 1 should be <None>, if not, well ....
					
					--IF EXISTS
					--	(
					--		SELECT 1
					--		FROM AO_Suppliers nolock
					--		WHERE AO_Suppliers_ID = 1
					--		AND Supplier_Name = '<None>'
					--	)
					--BEGIN
					--	IF @Supplier_ID <> 1
					--	BEGIN
					--		IF EXISTS	(
					--						SELECT 1
					--						FROM AP_Products nolock
					--						WHERE AP_Products_ID = @Product_ID
					--						AND Default_Supplier_ID = 1
					--					)
					--		BEGIN
					--			UPDATE AP_Products
					--			SET Default_Supplier_ID = @Supplier_ID,
					--				[User_ID] = @User_ID
					--			WHERE AP_Products_ID = @Product_ID
					--		END
					--	END
					--END
        		END
            
            ELSE
        		UPDATE AP_Products_Suppliers
                SET Trade_Disc_Perc = @TradeDiscPerc,
                    Trade_Disc_Date = @TradeDiscDate,
                    Lead_Time = @Lead_Time,
                    Start_Date = @StartDate,
                    AW_Trade_Discount_Formula_ID = @Trade_Disc_Formula_ID,
                    AW_Rebate_Discount_Formula_ID = @Rebate_Disc_Formula_ID,
                    Date_Captured = Getdate(),
                    [User_ID] = @User_ID
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID


        END

    ELSE
    IF @Choice = 1    --Update Changes
		UPDATE AP_Products_Suppliers
        SET Trade_Disc_Perc = @TradeDiscPerc,
            Trade_Disc_Date = @TradeDiscDate,
            Lead_Time = @Lead_Time,
            Start_Date = @StartDate,
            AW_Trade_Discount_Formula_ID = @Trade_Disc_Formula_ID,
            AW_Rebate_Discount_Formula_ID = @Rebate_Disc_Formula_ID,
            Date_Captured = Getdate(),
            [User_ID] = @User_ID
        WHERE AP_Products_ID = @Product_ID AND
              AO_Suppliers_ID = @Supplier_ID AND
              AW_User_Companies_ID = @Company_ID

    ELSE
    IF @Choice = 2    --Unlink Supplier
        IF EXISTS
            (
                SELECT AP_Products_Suppliers_ID
                FROM AP_Products_Suppliers
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID
            )
            BEGIN
        		DELETE AP_Products_Suppliers
                WHERE AP_Products_ID = @Product_ID AND
                      AO_Suppliers_ID = @Supplier_ID AND
                      AW_User_Companies_ID = @Company_ID
            END


	RETURN @New_ID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Document_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Insert
--Purpose       :INSERTS (SAVES) POS TRANSACTIONS
--Tables        :AS_Transactions
--Parameters    :
--Date          :2002/01/02
--Authors       :TB
--Version       :1.0.0
--MODS          :24/01/02 - Made CASH SALE Payment Transaction Number same as its
--              :            originating transaction
--              :15/04/02 - Update AC_Customers Account Balance
--              :26/02/04 - Added SET @Total_Cost = -(@Total_Cost) for Refunds
--              :           (TranType = 4) to correctly update C.O.S. GL Account
--              :           with net cost of POS Invoices and Credit Notes
--2004.5.3      :11/09/11 - Replaced input variable @Transmitted with @SmallComment
--              :           to match CDocument.mrsdata definitions in SpSPOSTrans
--              :           loaded from: vw_AS_POS_Transaction_Headers_Select and
--              :                        vw_AS_POS_Transaction_Headers_Select_Absolute
--RL	V6.3	:2017/09/25 - Send through @CustomerReference and @SmallComment
--RL	V6.3	:2017/09/25 - Used @VersionNumber to handel sales orders
-------------------------------------------------------------------------------


CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Insert]
    (
    	@DocumentID int = NULL output ,
    	@CustomerID int = NULL ,
    	@AccountID int = NULL ,
    	@No varchar(19) = NULL , -- TransactionNumber
    	@Total_Cost money = NULL ,
    	@Total_SubTotal money = NULL ,
    	@Total_Tax money = NULL ,
    	@Total_Discount money = NULL ,
    	@Total_Total money = NULL ,
    	@Payment money = NULL ,
    	@Date datetime = NULL ,
    	@ExpiryDate datetime = NULL ,
    	@VersionNumber int = NULL ,
    	@CustomerReference varchar(15) = NULL ,
    	@Comment varchar(500) = NULL ,
    	@TransactionTypeID int = NULL ,
    	--@MarketingIndicatorsID int = NULL ,
    	@StoreID int = NULL ,
    	@WorkstationID int = NULL ,
    	@TillID int = NULL ,
    	@CashierID int = NULL ,
    	@RepID int = NULL ,
    	@CurrencyID int = NULL ,
    	@OldTransactionTypeID int = NULL ,
    	@CancelledUserID int = NULL ,
    	@CancelledDate Datetime = NULL ,
    	@CashedUp Datetime = NULL ,
    	@DayEnd Datetime = NULL ,
--    	@Transmitted Datetime = NULL ,
    	@SmallComment varchar(20) = NULL ,
    	@DateCaptured Datetime = NULL ,
    	@UserID int = NULL ,
    	@CompanyID int = NULL ,
    	@CommentID int = NULL
    )

AS

	DECLARE @TransNum varchar(15)
	SET @DocumentID = 0

	IF ISNULL(@VersionNumber,0) = 0
		SET @VersionNumber = 0

	--Normal Document Creation
	IF ((@VersionNumber = 0) Or (@TransactionTypeID <> 16))
	BEGIN

		--SET @VersionNumber = 1
		SET @TransNum = @No            -- Assign TransactionNumber to @TransNum

		If @TransNum = '' OR @TransNum Is Null
			EXEC sp_AW_Get_Next_Transaction_Number @TransactionTypeID, @CompanyID, @No OUTPUT

		EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Comment

		IF @TransactionTypeID = 4 
			BEGIN
				SET @Total_Cost = -(@Total_Cost)
				SET @Total_SubTotal = -@Total_SubTotal
				SET @Total_Tax = -@Total_Tax
				SET @Total_Discount = -@Total_Discount
				SET @Total_Total = -@Total_Total
			END

		INSERT AS_Transactions
			(
				AC_Customers_ID,
				AB_Accounts_ID,
				Transaction_Number,
				Total_Cost,
				Amount,
				Total_Tax_Amount,
				Total_Discount_Amount,
				Total_Amount,
				Payment_Amount,
				--Transaction_Date,
				Expiry_Date,
				Version_Number,
				Customer_Reference,
				--Comments,
				Sys_AW_Transaction_Types_ID,
				--Lup_AS_Marketing_Indicators_ID,
				Lup_AW_Stores_ID,
				Lup_AW_Workstations_ID,
				Lup_AS_Tills_ID,
				Lup_AS_Cashiers_ID,
				Lup_AS_Reps_ID,
				Slu_AW_Currencies_ID,
				Old_Sys_AW_Transaction_Types_ID,
				Cancelled_User_ID,
				Cancelled_DateTime,
				Cashed_Up,
				Day_End,
				--Transmitted,
				--Date_Captured,
				Comment,
				User_ID,
				AW_User_Companies_ID,
				AW_Comments_ID
			)
		VALUES
			(
				@CustomerID,
				@AccountID,
				@No, -- TransactionNumber
				@Total_Cost,
				@Total_SubTotal,
				@Total_Tax,
				-@Total_Discount,
				@Total_Total,
				-(@Payment),
				--@Date,
				@ExpiryDate,
				1,
				@CustomerReference,
				--@Comments,
				@TransactionTypeID,
				--@MarketingIndicatorsID,
				@StoreID,
				@WorkstationID,
				@TillID,
				@CashierID,
				@RepID,
				@CurrencyID,
				@OldTransactionTypeID,
				@CancelledUserID,
				@CancelledDate,
				@CashedUp,
				@DayEnd,
				--@Transmitted,
				--@Date,
				@SmallComment,
				@UserID,
				@CompanyID,
				@CommentID
			)

		SELECT @DocumentID = Scope_Identity()

	--> Update the Customer Account Balance
		IF @TransactionTypeID = 3 OR @TransactionTypeID = 4
    		BEGIN	
    			UPDATE AC_Customers
				SET Account_Balance = Account_Balance + (@Total_Total - @Payment)
				WHERE AC_Customers_ID = @CustomerID
    		END
	END

	--Update Existing Sales Order
	IF ( (@VersionNumber = -99) OR (@VersionNumber = -88) )
	BEGIN
		IF @TransactionTypeID = 16
		BEGIN
			SELECT @DocumentID = AS_Transactions_ID
			FROM AS_Transactions
			WHERE   AC_Customers_ID = @CustomerID AND
					Customer_Reference = @CustomerReference AND
					SLU_AW_Active_ID = 1 AND
					AW_User_Companies_ID = @CompanyID AND
					Sys_AW_Transaction_Types_ID = 16
			ORDER BY Transaction_Date Asc

			UPDATE AS_Transactions
			SET Transaction_Date = GETDATE()
			WHERE AS_Transactions_ID = @DocumentID
		END
		--IF @VersionNumber = -99
		--BEGIN
		--	UPDATE AO_Order_Candidates
		--	SET Qty = Qty - Back_Order
		--	FROM AO_Order_Candidates o
		--		INNER JOIN AS_Transaction_Details d
		--			On o.AP_Products_ID = d.AP_Products_ID
		--	WHERE d.AS_Transactions_ID = @DocumentID AND
		--		Back_Order <> 0

		--	DELETE FROM AO_Order_Candidates
		--	WHERE Qty <= 0
		--END
	END	
	
	--Update Current Recalled Sales Order
	IF @VersionNumber > 0
	BEGIN
		UPDATE AO_Order_Candidates
		SET Qty = Qty - Back_Order
		FROM AO_Order_Candidates o
			INNER JOIN AS_Transaction_Details d
				On o.AP_Products_ID = d.AP_Products_ID
		WHERE d.AS_Transactions_ID = @VersionNumber AND
			Back_Order <> 0

		DELETE FROM AO_Order_Candidates
		WHERE Qty <= 0

		DELETE FROM AS_Transaction_Details 
		WHERE AS_Transactions_ID = @VersionNumber

		UPDATE AS_Transactions
		SET Total_Cost = 0,
			Amount = 0,
			Total_Tax_Amount = 0,
			Total_Discount_Amount = 0,
			Total_Amount = 0,
			Transaction_Date = GETDATE()
		WHERE AS_Transactions_ID = @VersionNumber

		SET @DocumentID = @VersionNumber
	END

RETURN @DocumentID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Insert_Transaction_Sources]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Insert_Transaction_Sources]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AS_Insert_Transaction_Sources
--Purpose       :ALTER  a list of AS_Transactions recalled source transaction numbers
--Date			:2004/02/02
--Authors		:TB
--Version		:1.0.0
--V6.3	RL		:2017/09/27 :Added check for duplicate Transaction_Number
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Insert_Transaction_Sources]
	(
		@ThisTranID int
	)

AS

SET NOCOUNT ON

    DECLARE @XrefID int,
            @TranID int,
            @TranNo varchar(19),
            @TranNoList varchar(200),
			@Found int


    SELECT @XrefID = AS_Transactions_Xref_ID
    FROM AS_Transactions_Xref
    WHERE AS_Transactions_ID = @ThisTranID

    SET @TranNoList = ''


--> CURSOR to concatenate Transaction Numbers in list
	DECLARE Transaction_Numbers CURSOR FOR
        (
            SELECT AS_Transactions_ID
            FROM AS_Transactions_Xref_Sources
            WHERE AS_Transactions_Xref_ID = @XrefID
        )


	OPEN Transaction_Numbers

    	FETCH NEXT FROM Transaction_Numbers 
    	INTO
            @TranID
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            SELECT @TranNo = Transaction_Number
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @TranID

			SET @Found = 0
			SELECT @Found = CHARINDEX(@TranNo, @TranNoList)

			IF @Found = 0
			BEGIN
				IF LEN(@TranNoList) > 0
					BEGIN
						SET @TranNoList = @TranNoList + ', '
					END

				SET @TranNoList = @TranNoList + @TranNo
			END

        	FETCH NEXT FROM Transaction_Numbers 
        	INTO
                @TranID

        END

	CLOSE Transaction_Numbers
	DEALLOCATE Transaction_Numbers

	IF NOT EXISTS
	(
		SELECT 1
		FROM AS_Transaction_Sources
		WHERE AS_Transactions_ID = @ThisTranID
		AND Transaction_Numbers = @TranNoList
	)
	BEGIN
	--> Insert the TranNo list 
		INSERT AS_Transaction_Sources
			(
				AS_Transactions_ID,
				Transaction_Numbers
			)
		VALUES
			(
				@ThisTranID,
				@TranNoList
			)
	END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Check_Till_Supervisor_Status]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Check_Till_Supervisor_Status]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Till_Supervisor_Status
--Purpose       :Select if User = Supervisor
--Functionality :User MUST BE IsTillPayout to authorise
--Date          :2017/10/19
--Authors       :RL
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Check_Till_Supervisor_Status]
	(
        @Password varchar(20),
		@TillSupervisor int OUTPUT
	)
AS

SET NOCOUNT ON

    SET @TillSupervisor = 0

	SELECT TOP 1 @TillSupervisor = AW_Users_ID
	FROM AW_Users
    WHERE IsTillPayout = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_Remote_Sites_IP]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_Remote_Sites_IP]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Sites_IP
--Purpose       :Retrieves Remote Sites Data Server and Instance Names
--Date          :2016-10-04
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_Remote_Sites_IP]
    (
		@NodeName  varchar(30),
        @CompanyID int,
        @ServerIP  varchar(250) OUTPUT 
    )

AS

SET NOCOUNT ON

	SELECT @ServerIP = DataServName + ISNULL(DataServIP1,'')
	FROM AW_Remote_Access 
	WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          NodeName = @NodeName

SET NOCOUNT OFF
GO
--Update Spiral Images
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\New_SpiralsoftADV1.bmp'
GO
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV2.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\New_SpiralsoftADV2.bmp'
GO
--Other
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Spiralsoft.bmp'
GO
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Spiralsoft150sbar.bmp'
GO
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Spiralsoft246pixH.bmp'
GO
UPDATE Sys_AW_Options
SET Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
WHERE Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Spiralsoft271pixH.bmp'
GO







IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_RPT_Payment_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_RPT_Payment_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Payment_Print
--Purpose       :POS Receipt printing
--Parameters    :
--Date          :2002/04/20
--Authors       :TB
--Version       :1
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--2004.2.4      :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.3	:2017-11-07 - Reworked Reg_No
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Payment_Print]
    (
    	@TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @WhichAddress tinyint,
            @WhichName tinyint,
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0


    SELECT TOP 1 @AddressOption0 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 0

    SELECT TOP 1 @AddressOption1 = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSPrintAddress' AND
          Control_Index = 1

    IF @AddressOption0 = 'True'
        BEGIN
            SET @WhichAddress = 0        --Print POSTAL Address
        END
    ELSE
    IF @AddressOption1 = 'True'
        BEGIN
            SET @WhichAddress = 1        --Print STREET Addres
        END


    SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSPrintTradeName'


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') as CustomerName,

    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
		ISNULL(c.Post_Box, '') AS [PostBox],
		ISNULL(c.Post_Office, '') AS [PostOffice],
		ISNULL(c.City, '') AS [PostCity],
		ISNULL(c.Post_Code, '') AS [PostCode],

		ISNULL(c.Street_Address, '') AS [StreetAddress],
		ISNULL(c.Suburb, '') AS [StreetSuburb],
		ISNULL(c.City, '') AS [StreetCity],
		ISNULL(c.Street_Post_Code, '') AS [StreetPostCode],

		ISNULL(c.Delivery_Address, '') AS [DeliverAddress],
		ISNULL(c.Delivery_Suburb, '') AS [DeliverSuburb],
		ISNULL(c.Delivery_City, '') AS [DeliverCity],
		ISNULL(c.Delivery_Post_Code, '') AS [DeliverPostCode],

		CONVERT(VARCHAR(12), c.AC_Customers_ID) AS [CustomerID], 
		ISNULL(c.Customer_Number, '') + '(' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + ')' as [CustomerNo],

        CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> ''
             THEN 'Merchant No: ' + RTRIM(LTRIM(c.Old_Customer_Number))
             ELSE ''
             END AS [MerchantNo],

        t.Sys_AW_Transaction_Types_ID AS [TranTypeID],
		tt.[Description] as TransactionType,
		comp.Tax_Number as CompanyTaxNumber,
		comp.Company_Name as CompanyName,
		comp.Company_Trading_Name AS TradingName,
		comp.Company_Addr1 as CompanyAddress1,
		comp.Company_Addr2 as CompanyAddress2,
		comp.Company_City as CompanyCity,
		comp.Company_Post_Code as CompanyPostCode,
        comp.Company_Registration_Number as CompanyRegNo,
        comp.Tel_No as CompanyTelNo,
        comp.Fax_No as CompanyFaxNo,
		rep.[Description] as RepName,
		t.AS_Transactions_ID as TransactionID,
		t.Transaction_Number as TransactionNo,
		CONVERT(varchar(12), t.Transaction_Date, 103) as TransactionDate,
		t.Customer_Reference as TransactionCustomerRef,
        t.Amount AS TransactionAmount,
		t.Total_Amount as TransactionTotalAmount,
		t.Total_Discount_Amount as TransactionTotalDiscount,
		t.Total_Tax_Amount as TransactionTotalTax,
		com.Comment AS TransactionComment,
-------------------------------------------------------------------------------
		pm.Description as PaymentMethod,
		tp.Payor_Name as PaymentPayorName,
		tp.Card_Expiry_Date as PaymentCardExpiry,
		tp.Card_Number as PaymentCardNo,
		tp.Authorisation_Number as PaymentAuthorisationNo,
		tp.Amount as PaymentAmount,
        CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + ':' +
        CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS TransactionTime,
        u.UserName as [UserCode],
--        t.SmallComment AS [Comment],
        t.Comment AS [Comment],
        t.AW_User_Companies_ID AS [CompanyID],
        @WhichAddress AS [AddressType],
        @WhichName AS [NameType],
	    ISNULL(ca.Reg_No, '') AS [Reg_No]

--	FROM vw_AS_Transactions t 
	FROM AS_Transactions t 
		LEFT JOIN AC_Customers c
            ON t.AC_Customers_ID = c.AC_Customers_ID
		LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
		LEFT JOIN AW_User_Companies comp
            ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID
		LEFT JOIN Lup_AS_Reps rep
            ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID
		LEFT JOIN AS_Transaction_Payments tp
            ON	t.AS_Transactions_ID = tp.AS_Transactions_ID
		LEFT JOIN Sys_AW_Payment_Methods pm
            ON tp.Sys_AW_Payment_Methods_ID = pm.Sys_AW_Payment_Methods_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
        LEFT JOIN AC_Assets ca
            ON t.AS_Transactions_ID = ca.AS_Transactions_ID   
	WHERE t.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Product_Catalog]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Product_Catalog]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Catalog
--Purpose       :select's a specific Product's Catalog information 
--Functionality :
--Parameters    :
--Date          :2001/12/07
--Authors       :TB
--MODS          :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--2004.2.3      :12/05/05 - Added GL_Purchases_ID AS [GLPurchasesID]
--              :                 GL_Sales_ID AS [GLSalesID]
--              :           for simultaneous 'Stock' and 'Non-Stock' GRV posting
--              :19/05/05 - Added Standard_Cost AS [Standard Cost]
--2004.2.4      :23/10/05 - Added GL_COS_ID AS [GLCOSID] for GL Cost-of-Sales
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories_ID AS [PurchaseCategory]
--2004.3.7      :25/07/07 - Added Lup_AP_Markup_Groups_ID AS [CostPlus Group]
--              :26/08/07 - Added Slu_AW_YesNo_Cost_Plus_Item AS [CostPlusItem]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_YesNo_Levy_Item As [IsLevy]
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_Weight_ID As [ProductWeight]        
--2004.5.7 RGL  :2012-10-17 - Added Levy_Product_ID AS [Levy_Product]
--2004.6.0 RGL  :2014-04-10 - Added Slu_AW_YesNo_Sell_Below_Cost AS [Sell Below Cost]
--2004.6.0 RGL  :2014-05-07 - Changed On Hand, Job Reserved, On order and Sales Order values to 
--			      include transactions that could affect value
--V6.2 RL  :2015-06-10 - Added quantity of products out on consignment
---------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Catalog]
    (
        @Product_ID int,
        @Company_ID int 
    )
AS

SET NOCOUNT ON

    SELECT AP_Products_ID AS [ID], 
    	[Description] AS [Description], 
    	Print_Description AS [Print Description], 
    	Keywords AS [Search Keywords], 
    	Lup_AP_Product_Types_ID AS [Type], 
    	Lup_AP_Product_Groups_ID AS [Group], 
    	Lup_AP_Product_Departments_ID AS [Department], 
    	Lup_AP_Product_Locations_ID AS [Location], 
    	Lup_AP_Purchase_Categories_ID AS [PurchaseCategory], 
    	Serial_Number AS [Serial Number], 
    	Lup_AP_Product_Manufacturers_ID AS [Manufacturer], 
    	Manufacturer_Code AS [Manuf Code], 
    	Manufacturer_Description AS [Manuf Description], 
    	Default_Supplier_ID AS [Default Supplier], 
    	Product_Code AS [Product Code], 
    	SKU_Code AS [LCD Code], 
    	Supercession AS [Supercession], 
    	Alternate_Code1 AS [Alt Code 1], 
    	Alternate_Code2 AS [Alt Code 2],
     	Pack_Size AS [Pack Size], 
    	Measure AS [Measure], 
    	Slu_AP_Units_Of_Measure_ID AS [Unit of Measure], 
    	Strength AS [Unit Strength], 
    	Lup_AP_Mass_Codes_ID AS [Mass Code], 
    	Pack_Mass AS [Pack Mass], 
    	Pack_Volume AS [Pack Volume], 
    	Slu_AW_Active_ID AS [Active], 
    	Slu_AW_YesNo_Self_Managed AS [Self Managed], 
    	Price1_Effective_Date AS [Price 1 - Effective Date], 
    	Price1_Price1 AS [Price 1 - Price1], 
    	Price1_Price2 AS [Price 1 - Price2], 
    	Price2_Effective_Date AS [Price 2 - Effective Date], 
    	Price2_Price1 AS [Price 2 - Price1], 
    	Price2_Price2 AS [Price 2 - Price2], 
    	Lup_AP_Rounding_Codes_ID AS [Rounding Code], 
    	Sys_AW_Tax_Codes_ID AS [Tax Code], 
    	Lup_AP_Discount_Groups_ID AS [Sales Discount Group], 
    	Lup_AP_Markup_Groups_ID AS [CostPlus Group], 
    	Lup_AP_Commission_Groups_ID AS [Sales Commission Group], 
    	Slu_AW_YesNo_Edit_Price AS [Edit Price at POS], 
    	Slu_AW_YesNo_Edit_Discount AS [Edit Discount at POS], 
    	Max_Discount_Perc AS [MaxDiscPerc], 
    	Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc], 
    	PLU_Tab AS [Plu Tab Location], 
    	Lup_AP_Sell_By_Codes_ID AS [Sell By Code], 
    	--On_Hand AS [Qty On Hand], 
		--CONVERT(decimal(9, 3),(On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(AP_Products_ID))) as [Qty on Hand],
		On_Hand as [Qty on Hand],
    	--Job_Reserved AS [Job Reserved],
		CONVERT(decimal(18, 3), dbo.fn_AP_Products_Job_Reserved(AP_Products_ID)) as [Job Reserved], 
    	--Quote_Reserved AS [Quote Reserved],
    	CONVERT(decimal(18, 3), dbo.fn_AP_Products_Quoted(AP_Products_ID)) as [Quote Reserved], 
    	--Sales_Order_Reserved AS [Sales Order Reserved],
    	CONVERT(decimal(18, 3), dbo.fn_AP_Products_Sales_Order_Reserved(AP_Products_ID)) as [Sales Order Reserved], 
    	CONVERT(decimal(18, 3), dbo.fn_AP_Get_Products_Out_On_Consignment(AP_Products_ID)) as [Out On Consignment], 
    	Min_Stock_Level AS [Min Stock Level], 
    	Last_Cost AS [Last Cost], 
    	Average_Cost AS [Average Cost], 
    	Standard_Cost AS [Standard Cost], 
    	Average_Markup AS [Average Markup %], 
    	Last_Sale_Date AS [Last Sale Date], 
    	Service_Level AS [Service Level], 
    	Max_Order_Qty AS [Max_Order_Qty], 
    	Min_Order_Qty AS [Min_Order_Qty],
    	--(SELECT (SUM(od.Order_Qty)+ SUM(od.Back_Order_Qty) - SUM(od.Received_Qty))
    	--        FROM AO_Order_Details od INNER JOIN AO_Orders o
    	--            ON od.AO_Orders_ID = o.AO_Orders_ID
    	--        WHERE o.Date_Ordered is not null AND
    	--              o.Complete <> 1 AND
    	--              od.AP_Products_ID = @Product_ID) AS [Qty on order],
		CONVERT(decimal(18, 3), dbo.fn_AO_Get_Qty_On_Order(AP_Products_ID)) as [Qty on order],
    	Slu_AW_YesNo_Assembly AS [Yes No Assembly],	
    	Memo AS [Notes], 
    	Show_Image AS [Show Image], 
    	Image_File_Name AS [Image Path], 
        Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--        Slu_AW_YesNo_Hide_Remote AS [HideRemote],
        Slu_AW_YesNo_Cost_Plus_Item AS [CostPlusItem],
        GL_Purchases_ID AS [GLPurchasesID],
        GL_Sales_ID AS [GLSalesID],
        GL_COS_ID AS [GLCOSID],      
        Lup_AP_AW_Weight_ID As [Weight Code],
        Product_Weight As [Product Weight],                       
        Slu_AW_YesNo_Levy_Item As [IsLevy],        
        Levy_AP_Product_ID AS [Levy Product],
        Levy_Weight_ID As [Levy Weight Code],    
        Slu_AW_YesNo_Sell_Below_Cost AS [Sell Below Cost],     
    	Date_Captured AS [Date Captured], 
    	[User_ID] AS [User ID], 
    	AW_User_Companies_ID AS [Company ID] 

    FROM AP_Products 
    WHERE AP_Products_ID = @Product_ID AND 
    	AW_User_Companies_ID = @Company_ID

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Product_Catalog_Non_Stock]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Product_Catalog_Non_Stock]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Catalog_Non_Stock
--Purpose       :Fetch all Non-Stock Products from Catalog
--Functionality :
--Date          :2009/04/30
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Catalog_Non_Stock]
    (
         @CompanyID int 
    )

AS

SET NOCOUNT ON

	SELECT
        AW_User_Companies_ID AS [CompanyID],
        AP_Products_ID AS [ProductID],
		Description AS [Description], 
		ISNULL(Product_Code, '') AS [Code], 
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) AS [Unit Price],
		Last_Cost AS [Last Cost], 
		Average_Cost AS [Avg Cost], 
		Standard_Cost AS [Std Cost],
		On_Hand AS [On Hand],
        CONVERT(decimal(18, 3), dbo.fn_AP_SUM_Product_Job_Reserved(AP_Products_ID)) AS [Reserved]
	FROM AP_Products
    WHERE AW_User_Companies_ID =  @CompanyID AND
          Slu_AW_YesNo_Non_Stock_Item = 1



SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Filtered_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Filtered_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Filtered_Products
--Purpose       :Stock Receipts Product Search
--Date          :2002/04/16
--Authors       :TB
--Mods          :16/05/02 - Removed top 100 in SELECT
--              :18/04/02 - A Single Criteria search did not include
--              :           a search on Product_Code
--              :28/04/02 - Fixed @Criteria3, @criteria2, @criteria1 filters
--              :07/07/03 - Added filter to EXCLUDE all Non-Stock items
--              :06/03/05 - Added FETCH only ACTIVE products
--              :14/05/05 - Added [Purchases Account] for Product-Assigned GL Accounts
--2004.3.7      :22/11/07 - Added [Std. Cost], [Std. Disc1], [Std. Disc2] using
--              :           Standard Cost as default purchase price
--2004.4.8      :28/03/10 - Added WILDCARD Pattern Matching using _ (underscore) character
--              :           in Normal Search (@SearchType = 0) for the 3 @Filter(n)
--              :03/08/10 - Fixed to EXCLUDE NON-ACTIVE products bypassed by WILDCARD Pattern Matching
--        ****  :02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section and reworked script
--        ****  :02/09/10 - REMOVED WILDCARD search
--RL			:2013-07-15 - Added Alternate_Code1, Alternate_Code2 and Keyword to search fields
--V6.0	RL		:2014-10-28 - Reworked Job, Quote Reserved
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Filtered_Products]
    (
       @CompanyID int,
       @FilterType int = -1,
       @FilterValue int = -1,
       @Criteria1 varchar(50) = '',
       @Criteria2 varchar(50) = '',
       @Criteria3 varchar(50) = ''
    )

AS

SET NOCOUNT ON


    DECLARE @Criteria varchar(4000), 
            @SQL varchar(8000),
            @Wildcard varchar(50),
            @wc1 varchar(50),
            @wc2 varchar(50)



    SET @Criteria = ''
    SET @Wildcard = ''
    SET @wc1 = ''
    SET @wc2 = ''

--     --> WILDCARD Pattern Matching using _ (underscore) character
--     IF LTRIM(RTRIM(@Criteria1)) <> '' AND ISNUMERIC(@Criteria1) > 0
--         BEGIN
--             SET @wc1 = REPLACE(LTRIM(RTRIM(@Criteria1)), '/', '')
--             SET @wc2 = REPLACE(@wc1, '-', '')
--             IF LEN(@wc2) >= 5 AND ISNUMERIC(LEFT(@wc2, 3)) > 0
--                 BEGIN
--                     SET @Wildcard = 
--                         CASE LEN(@wc2)
--                              WHEN 5 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2)
--                              WHEN 6 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 1)
--                              WHEN 7 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '_' + RIGHT(@wc2, 2)
--                              WHEN 8 THEN LEFT(@wc2, 3) + '_' + SUBSTRING(@wc2, 4, 2) + '__' + RIGHT(@wc2, 2)
--                         END    
--                     SET @Wildcard = '''%' + @Wildcard + '%'''
--                 END
--         END

    SET @Criteria = ' WHERE p.AW_User_Companies_ID = ' + convert(varchar(10), @CompanyID) + 
                    ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 ' +        --> EXCLUDE Non-Stock items (07/07/03)
                    ' AND p.Slu_AW_Active_ID = 1 '                     --> INCLUDE only ACTIVE products (06/03/05)

    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria3 = '''%' +  @Criteria3 + '%'''
        END

    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria2 = '''%' +  @Criteria2 + '%'''
        END

    IF @Criteria1 <> ''
        BEGIN
            SET @Criteria1 = '''%' +  @Criteria1 + '%'''
        END


    IF @Criteria3 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND ((p.Description Like ' + @Criteria3 + ' and p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria3 + ' and p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' ) OR
                                  
                                  (p.Alternate_Code1 Like ' + @Criteria3 + ' and p.Alternate_Code1 Like ' + @Criteria2 + ' and p.Alternate_Code1 Like ' + @Criteria1 + ' ) OR
                                  (p.Alternate_Code2 Like ' + @Criteria3 + ' and p.Alternate_Code2 Like ' + @Criteria2 + ' and p.Alternate_Code2 Like ' + @Criteria1 + ' ) OR
                                  (p.Keywords Like ' + @Criteria3 + ' and p.Keywords Like ' + @Criteria2 + ' and p.Keywords Like ' + @Criteria1 + ' )) '
                                  
        END
    ELSE
    IF @Criteria2 <> ''
        BEGIN
            SET @Criteria = @Criteria +
                            ' AND ((p.Description Like ' + @Criteria2 + ' and p.Description Like ' + @Criteria1 + ') OR
                                  (p.Product_Code Like ' + @Criteria2 + ' and p.Product_Code Like ' + @Criteria1 + ' ) OR
                                  
                                  (p.Alternate_Code1 Like ' + @Criteria2 + ' and p.Alternate_Code1 Like ' + @Criteria1 + ' ) OR
                                  (p.Alternate_Code2 Like ' + @Criteria2 + ' and p.Alternate_Code2 Like ' + @Criteria1 + ' ) OR
                                  (p.Keywords Like ' + @Criteria2 + ' and p.Keywords Like ' + @Criteria1 + ' )) '
        END
    ELSE
    IF @Criteria1 <> ''        --02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section
        BEGIN
--             IF @Wildcard <> ''
--                 BEGIN
--                     SET @Criteria = @Criteria + ' AND (p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' OR p.Description Like ' + @Wildcard + ' OR p.Product_Code Like ' + @Wildcard + ' )'
--                 END
--             ELSE
--                 BEGIN
                    SET @Criteria = @Criteria + ' AND ((p.Description Like ' + @Criteria1 + ' OR p.Product_Code Like ' + @Criteria1 + ' OR
													p.Alternate_Code1 Like ' + @Criteria1 + ' OR p.Alternate_Code2 Like ' + @Criteria1 + ' Or
													p.Keywords Like ' + @Criteria1 + '))'
--                 END
        END


    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
    SET @SQL = @SQL + ' p.Description, '
    SET @SQL = @SQL + ' p.Product_Code AS [Code], '
    SET @SQL = @SQL + ' p.On_Hand AS [Qty on Hand], '

    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price 1], '
    SET @SQL = @SQL + ' p.Standard_Cost AS [Std. Cost], '
    SET @SQL = @SQL + ' p.Standard_Disc1 AS [Std. Disc1], '
    SET @SQL = @SQL + ' p.Standard_Disc2 AS [Std. Disc2], '
    SET @SQL = @SQL + ' p.Last_Cost AS [Last Cost], '
    SET @SQL = @SQL + ' p.Average_Cost AS [Avg Cost], ' 

    SET @SQL = @SQL + ' dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost) AS [GP %], '
    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) AS [Price 2], '
    SET @SQL = @SQL + ' p.Pack_Size AS [Qty], '
    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price], '
    SET @SQL = @SQL + ' p.Print_Description AS [Print], ' 
    SET @SQL = @SQL + ' p.SKU_Code AS [Other Code], ' 
    SET @SQL = @SQL + ' p.Measure, ' 
    SET @SQL = @SQL + ' uof.Description AS [Unit], ' 
    SET @SQL = @SQL + ' p.Manufacturer_Code AS [Manuf Code], ' 
    SET @SQL = @SQL + ' p.Manufacturer_Description AS [Manuf Description], ' 
    SET @SQL = @SQL + ' pt.Description AS [ProductType], ' 
    SET @SQL = @SQL + ' pg.Description AS [Group], ' 
    SET @SQL = @SQL + ' pd.Description AS Department, ' 
    SET @SQL = @SQL + ' pl.Description AS Location, ' 
    SET @SQL = @SQL + ' p.Alternate_Code1 AS [Alt Code1], ' 
    SET @SQL = @SQL + ' p.Alternate_Code2 AS [Alt Code2], ' 
    SET @SQL = @SQL + ' p.Supercession, ' 
    SET @SQL = @SQL + ' p.Pack_Volume AS [Pack Volume], ' 
    SET @SQL = @SQL + ' mc.Description AS [Mass Code], ' 
    SET @SQL = @SQL + ' p.Pack_Mass AS [Pack Mass], ' 
    SET @SQL = @SQL + ' p.Strength, ' 
    SET @SQL = @SQL + ' p.Min_Stock_Level AS [Min Stock Level], ' 
    SET @SQL = @SQL + ' p.Last_Sale_Date AS [Last Sale Date], ' 
    SET @SQL = @SQL + ' p.Service_Level AS [Service Level], ' 
    SET @SQL = @SQL + ' p.Max_Order_Qty AS [Max Order Qty], ' 
    SET @SQL = @SQL + ' p.Min_Order_Qty AS [Min Order Qty], ' 
    SET @SQL = @SQL + ' p.Serial_Number AS [Serial No], ' 
    SET @SQL = @SQL + ' p.Sys_AW_Tax_Codes_ID AS [Tax_Code_ID], '
    SET @SQL = @SQL + ' CONVERT(decimal(18, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) AS [Job Reserved], '
    SET @SQL = @SQL + ' CONVERT(decimal(18, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) AS [Quote Reserved], '
    SET @SQL = @SQL + ' p.Date_Captured AS [Date], ' 
    SET @SQL = @SQL + ' p.User_ID AS [UserID], ' 
    SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID] '

    SET @SQL = @SQL + ' FROM AP_Products p '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc            ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Locations pl     ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Departments pd   ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Types pt         ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Groups pg        ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Slu_AP_Units_Of_Measure uof     ON p.Slu_AP_Units_Of_Measure_ID = uof.Slu_AP_Units_Of_Measure_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Manufacturers pm ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '


    SET @SQL = @SQL + @Criteria


 	IF @FilterType = 1    --> Suppliers
        SET @SQL = @SQL + ' AND p.AP_Products_ID in (SELECT AP_Products_ID FROM AP_Products_Suppliers WHERE AO_Suppliers_ID = ' + Convert(Varchar(10), @FilterValue) + ') '
	ELSE 
	IF @FilterType = 2    --> Manufacturer
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Manufacturers_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 3    --> Type
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Types_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 4    --> Group
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Groups_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 5    --> Department
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Departments_ID = ' + Convert(Varchar(10), @FilterValue) 
	ELSE 
	IF @FilterType = 6    --> Location
        SET @SQL = @SQL + ' AND p.Lup_AP_Product_Locations_ID = ' + Convert(Varchar(10), @FilterValue) 


    EXEC (@SQL)
    --Select @SQL

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Cash_Book_Recon_History]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Cash_Book_Recon_History]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Cash_Book_Recon_History
--Purpose       :Returns Cash Book Reconciliation Transactions
--              :for specific Bank, Transaction Type, Accounting Period
--Functionality :Select
--Parameters    :
--Date          :2002/11/23
--Authors       :TB
--MODS          :27/11/02 - Removed Recon-Chk field
--              :09/01/03 - Changed SORT ORDER to TranType, TranDate
--2004.4.9      :22/09/10 - Added NEW input parameters @Month_ID and @Year_ID to fetch
--              :           RECONCILED transactions for ONE Accounting Period
--V6.4	RL	2018/02/07	:Added Sys_AB_Transaction_Types_ID 30 - Cash Book - Tax Payment
--V6.4	RL	2018/02/07	:Added Sys_AB_Transaction_Types_ID 31 - Cash Book - Tax Received
-------------------------------------------------------------------------------
-- NB: Actual DB Column** assignments to Aliases below is REQUIRED for setting
--     (adding or assigning) ADO Field.Values in the recordset
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Select_Cash_Book_Recon_History]
    (
        @Company_Banks_ID int,
    	@Company_ID int,
        @Reconciled tinyint,
    	@Month_ID tinyint,
        @Year_ID smallint,
        @Option tinyint
    )

AS

SET NOCOUNT ON


--> Unreconciled Transactions
    IF @Reconciled = 0
        BEGIN
        --> Cheques and other Debits
            IF @Option = 0
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 

                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
                     (tt.Sys_AB_Transaction_Types_ID = 9 OR         --Cash Book - Cheque
                      tt.Sys_AB_Transaction_Types_ID = 11 OR        --Cash Book - Interest Paid
                      tt.Sys_AB_Transaction_Types_ID = 12 OR        --Cash Book - Bank Charge
                      tt.Sys_AB_Transaction_Types_ID = 13 OR        --Credit Card - Charge
                      tt.Sys_AB_Transaction_Types_ID = 14 OR        --Credit Card - Payment
                      tt.Sys_AB_Transaction_Types_ID = 18 OR        --Cash Book - Debit Order
                      tt.Sys_AB_Transaction_Types_ID = 20 OR        --Cash Book - EFT Payment
                      tt.Sys_AB_Transaction_Types_ID = 21 OR		--Cash Book - EFT Payment          --Cash Book - Buy Association
					  tt.Sys_AB_Transaction_Types_ID = 30 OR		--Cash Book - Tax Payment       
					  tt.Sys_AB_Transaction_Types_ID = 31)			--Cash Book - Tax Received       
                ORDER BY tt.Transaction_Code, t.Transaction_Date  

        --> Deposits and other Credits
            ELSE
            IF @Option = 1
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 
    
                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      ISNULL(t.Recon_Amount, 0) <> ISNULL(t.Amount, 0) AND
                     (tt.Sys_AB_Transaction_Types_ID = 10 OR        --Cash Book - Deposit
                      tt.Sys_AB_Transaction_Types_ID = 17 OR        --Cash Book - Interest Received
                      tt.Sys_AB_Transaction_Types_ID = 19)          --Cash Book - EFT Deposit
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        END

--> Reconciled Transactions
    ELSE
    IF @Reconciled = 1
        BEGIN
        --> Cheques and other Debits
            IF @Option = 0
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 

                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      t.Slu_AW_Months_ID = @Month_ID AND
                      t.Slu_AW_Years_ID = @Year_ID AND
                     (t.Sys_AB_Transaction_Types_ID = 9 OR         --Cash Book - Cheque
                      t.Sys_AB_Transaction_Types_ID = 11 OR        --Cash Book - Interest Paid
                      t.Sys_AB_Transaction_Types_ID = 12 OR        --Cash Book - Bank Charge
                      t.Sys_AB_Transaction_Types_ID = 13 OR        --Credit Card - Charge
                      t.Sys_AB_Transaction_Types_ID = 14 OR        --Credit Card - Payment
                      t.Sys_AB_Transaction_Types_ID = 18 OR        --Cash Book - Debit Order
                      t.Sys_AB_Transaction_Types_ID = 20 OR        --Cash Book - EFT Payment
                      t.Sys_AB_Transaction_Types_ID = 21 OR          --Cash Book - Buy Association
					  t.Sys_AB_Transaction_Types_ID = 30 OR			--Cash Book - Tax Payment       
					  t.Sys_AB_Transaction_Types_ID = 31)			--Cash Book - Tax Received       
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        --> Deposits and other Credits
            ELSE
            IF @Option = 1
                SELECT
                    t.AB_Cash_Book_Transactions_ID AS [ID], 
    
                --> Actual DB Column assignments is REQUIRED for setting ADO Field.Values
                ----------------------------------------------------
                    t.Recon_Amount AS [Reconciled],
                    t.Amount AS [Balance],
                    t.Amount AS [Amount], 
                ----------------------------------------------------
                    tt.Transaction_Code AS [Type],
                    t.Reference_No AS [Ref No], 
                    t.Transaction_Date AS [Date], 
                    m.[Description] AS [Month], 
                    y.[Description] AS [Year],
                    t.Transaction_Description AS [Description],
                   (t.Amount - t.Recon_Amount) AS [OldBalance]
                FROM AB_Cash_Book_Transactions t
                    LEFT JOIN Sys_AB_Transaction_Types tt
                    	ON t.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID
                    LEFT JOIN AW_Company_Banks b
                    	ON t.AW_Company_Banks_ID = b.AW_Company_Banks_ID
                    LEFT JOIN Slu_AW_Months m
                    	ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                    	ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                WHERE t.AW_Company_Banks_ID = @Company_Banks_ID AND 
                      t.AW_User_Companies_ID = @Company_ID AND
                      t.Slu_AW_Months_ID = @Month_ID AND
                      t.Slu_AW_Years_ID = @Year_ID AND
                     (t.Sys_AB_Transaction_Types_ID = 10 OR        --Cash Book - Deposit
                      t.Sys_AB_Transaction_Types_ID = 17 OR        --Cash Book - Interest Received
                      t.Sys_AB_Transaction_Types_ID = 19)          --Cash Book - EFT Deposit
                ORDER BY tt.Transaction_Code, t.Transaction_Date 

        END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_Users]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_Users]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Select_Users
--Purpose       :Select Users and Company Users
--              :
--Tables        :AW_Users, AW_Company_Users, AW_User_Companies
--Parameters    :
--Date          :2002/02/21
--Authors       :TB
--MODS          :08/09/02 - Added 'Trading Name' for SMS and eMail CComms
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------


CREATE Procedure [dbo].[sp_AW_Select_Users]

AS

SET NOCOUNT ON

    SELECT
        U.AW_Users_ID AS [User ID],
        U.UserName AS [User Name],
        U.Password AS [Password],
        U.Surname AS Surname,
        U.FirstName AS [First Name], 
        U.Slu_AW_Active_ID AS [Active User],
        UC.AW_User_Companies_ID AS [Company ID], 
        UC.Company_Name AS [Company Name],
        U.Sys_AW_Applications_ID AS [Applications],
        UC.Company_Trading_Name AS [Trading Name],
        ISNULL(U.User_Email,'') AS [User Email]
    FROM AW_Users U
        INNER JOIN dbo.AW_Company_Users CU
        	ON U.AW_Users_ID = CU.AW_Users_ID 
        INNER JOIN dbo.AW_User_Companies UC 
        	ON CU.AW_User_Companies_ID = UC.AW_User_Companies_ID
--     WHERE CU.Slu_AW_Active_ID <> 0 AND
--           UC.Slu_AW_Active_ID <> 0
    WHERE U.Slu_AW_Active_ID = 1
    ORDER BY UC.Yes_No_Default_Company DESC, UC.Company_Name

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Payment_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Select
--Purpose       :POS Payment Transaction Header
--              :
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Select]
	(
        @DocumentID int
    )

AS

SET NOCOUNT ON

	SELECT 
		t.AS_Transactions_ID as PaymentID, 
		t.AC_Customers_ID as CustomerID, 
		t.AB_Accounts_ID as AccountID, 
		t.Transaction_Number as TransactionNumber, 
		--Total_Cost as Cost, 						--These fields are appended in a shape to be calculated
		--Amount as Amount, 
		--Total_Tax_Amount as Tax, 
		--Total_Discount_Amount as Discount, 
		--Total_Amount as TotalAmount, 
		--Payment_Amount as PaymentAmount, 
		t.Customer_Reference as CustomerReference, 
		--t.Comments, 
		t.Sys_AW_Transaction_Types_ID as TransactionTypeID, 
		t.Lup_AW_Stores_ID as StoreID, 
		t.Lup_AW_Workstations_ID as WorkstationID, 
		t.Lup_AS_Tills_ID as TillID, 
		t.Lup_AS_Cashiers_ID as CashierID, 
		t.Lup_AS_Reps_ID as RepID, 
		t.Slu_AW_Currencies_ID as CurrencyID, 
		t.Date_Captured as DateCaptured,  
		t.User_ID as UserID,  
		t.AW_User_Companies_ID as CompanyID,
		tt.Source_AS_Transactions_ID as SourceTransactionID
    FROM AS_Transactions t 
		INNER JOIN AS_Transactions_Transactions tt
			ON t.AS_Transactions_ID = tt.Source_AS_Transactions_ID
    WHERE t.AS_Transactions_ID = @DocumentID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Payment_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Insert
--Purpose       :Inserts POS Payment Transactions (TranTypeID = 4)
--SEE ALSO      :sp_AS_Transaction_Payment_Insert (Back Office Payment insert)
--Functionality :INSERTS: AS_Transactions, AS_Transactions_Transactions
--              :UPDATES: AC_Customers
--Date          :2002/01/23
--Authors       :TB
--MODS          :
--2004.3.8      :29/05/08 - Replaced errorneous ABS(@TotalAmount) insert into
--              :           AS_Transactions_Transactions with -@TotalAmount to insert
--              :           the SAME value as inserted in AS_Transactions for
--              :           TranType 7 (POS Payments). ABS(@TotalAmount) inserted
--              :           the SAME SIGNED value for POSITIVE AND NEGATIVE payments !!!
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Insert]
	(
        @PaymentID int OUTPUT,
        @CustomerID int = NULL,
        @AccountID int = NULL,
        @TransactionNumber varchar(19) = NULL,
        @TotalAmount money = 0,
        @PaymentAmount money = 0,
        @CustomerReference varchar(15) = NULL,
        @TransactionTypeID int = NULL,
        @StoreID int = NULL,
        @WorkstationID int = NULL,
        @TillID int = NULL,
        @CashierID int = NULL,
        @RepID int = NULL,
        @CurrencyID int = NULL,
        @DateCaptured datetime = NULL,
        @UserID int = NULL,
        @CompanyID int = NULL,
        @SourceTransactionID int = NULL
 
	)
AS

SET NOCOUNT ON

	DECLARE
        @CommentID int,
        @SourceTransactionTypeID int,
        @TransNum varchar(19)
        
        
	SELECT @SourceTransactionTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @SourceTransactionID
        

    SET @TransNum = @TransactionNumber        

    --> Fetch only if no Transaction Number passed in
    IF @TransNum = '' OR @TransNum Is Null
        EXEC sp_AW_Get_Next_Transaction_Number
                        @TransactionTypeID,
                        @CompanyID,
                        @TransactionNumber OUTPUT
------------------------------------------------
        
	IF @SourceTransactionTypeID = 4    -- Refund
		BEGIN
			SET @TotalAmount = -@TotalAmount
			SET @PaymentAmount = -@PaymentAmount
		END

	--V6.4 RL
	--This is a dirty fix for i-Pay. Needs to be done properly in Elite
	--Not enough time to do it properly
	--There is a scenario were the user can allocate another payment to an i-Pay pay later transaction
	--In this case we don't want to allocate the payment to the invoice as it will over allocate it.
	--We just capture the payment and the user needs to go allocate it.
	 
	IF ISNULL(@CurrencyID,0) = 99
	BEGIN
		SET @PaymentAmount = 0
	END

	INSERT AS_Transactions
		(
			AC_Customers_ID,
			AB_Accounts_ID,
			Transaction_Number,
			Amount, 
			Total_Amount,
			Payment_Amount,
			Customer_Reference,
			Sys_AW_Transaction_Types_ID,
			Lup_AW_Stores_ID,
			Lup_AW_Workstations_ID,
			Lup_AS_Tills_ID,
			Lup_AS_Cashiers_ID,
			Lup_AS_Reps_ID,
			Slu_AW_Currencies_ID,
			[User_ID],
			AW_User_Companies_ID
		)
	VALUES
		(
			@CustomerID,
			@AccountID,
			@TransactionNumber,
			-(@TotalAmount),
			-(@TotalAmount),
			@PaymentAmount,
			@CustomerReference,
			7,
			@StoreID,
			@WorkstationID,
			@TillID,
			@CashierID,
			@RepID,
			NULL,--@CurrencyID,
			@UserID,
			@CompanyID
		)

	SELECT @PaymentID = Scope_Identity()

	IF ISNULL(@CurrencyID,0) <> 99
	BEGIN
		--> Update the ORIGINAL transaction's Payment Amount
		UPDATE AS_Transactions
		SET Payment_Amount = Payment_Amount - @PaymentAmount
		WHERE AS_Transactions_ID = @SourceTransactionID

		INSERT AS_Transactions_Transactions 
			(
				Source_AS_Transactions_ID,
				Destination_AS_Transactions_ID,
				Amount
			)
		VALUES
			(
				@SourceTransactionID,
				@PaymentID,
	--            ABS(@TotalAmount)
				-@TotalAmount
			)

		--> UPDATE Customer Account Balance
		UPDATE AC_Customers
		SET Account_Balance = Account_Balance - @TotalAmount
		WHERE AC_Customers_ID = @CustomerID
	END
	
    RETURN @PaymentID

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Payment_Details_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Details_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Payment_Details_Select
--Purpose       :POS Payment Transaction Details
--Functionality :NB NB: The order of fields are determined by the order in the tally 
--Date          :2002/01/29
--Authors       :TB
--Version       :1.0.0
--MODS          :
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Details_Select]
    (
        @PaymentID int
    )

AS

SET NOCOUNT ON

    SELECT 
        m.Description AS [Method],
        i.Description AS [Institution],
        p.Amount AS [Amount], 
        p.Payor_Name AS [PayorName], 
        p.Card_Expiry_Date AS [CardExpiryDate], 
        p.Card_Number AS [CardNo], 
        p.Authorisation_Number AS [AuthorisationNo], 
        p.Sys_AW_Payment_Methods_ID AS [MethodID], 
        p.Slu_AS_Card_Institutions_ID AS [InstitutionID], 
        p.Date_Captured AS [Date], 
        p.[User_ID] AS [UserID], 
        p.AW_User_Companies_ID AS [CompanyID],
        p.AS_Transaction_Payments_ID AS [PaymentDetailsID],
        p.AS_Transactions_ID AS [PaymentID],
        p.Date_Captured AS [Date],
		y.IPay_ID as [IPay_ID],
		y.IPay_Tran_Ref As [IPay_Tran_Ref],
		y.IPay_Bank_Ref As [IPay_Bank_Ref],
        y.IPay_Status As [IPay_Status],
        y.Cell_No As [Cell_No],
        y.Email	As [Email]
        
    FROM AS_Transaction_Payments p
        LEFT JOIN Sys_AW_Payment_Methods m
            ON p.Sys_AW_Payment_Methods_ID = m.Sys_AW_Payment_Methods_ID
        LEFT JOIN Slu_AS_Card_Institutions i
            ON p.Slu_AS_Card_Institutions_ID = i.Slu_AS_Card_Institutions_ID
        LEFT JOIN AS_Transaction_Payments_IPay y
			ON p.AS_Transaction_Payments_ID = y.AS_Transaction_Payments_ID
    WHERE p.Slu_AW_Active_ID = 1 AND
          p.AS_Transactions_ID = @PaymentID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   : sp_AS_POS_Transaction_Payment_Detail_Insert
--Purpose       : Inserts POS Payment Transaction Details (TranTypeID = 4)
--Functionality : Tables: AS_Transaction_Payments
--Parameters    : 
--Date          : 2002/01/29
--Authors       : TB
--Version       :
--V6.4	RL	2018-03-07	:Add IPay
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Payment_Detail_Insert]
	(					
		@Amount				money = NULL,	
		@PayorName			varchar(50) = NULL,
		@CardExpiryDate		varchar(6) = NULL,
		@CardNo				varchar(20) = NULL,
		@AuthorisationNo	varchar(20) = NULL,
		@MethodID			int = NULL,
		@InstitutionID		int = NULL,
		@UserID				int = NULL,
		@CompanyID			int = NULL,
		@PaymentDetailsID	int = NULL,
		@PaymentID			int = NULL,
		@Date				dateTime = NULL,
        @IPay_ID			varchar(50),
        @IPay_Tran_Ref		varchar(50),
        @IPay_Bank_Ref		varchar(50),
        @IPay_Status		int,
        @Cell_No			varchar(20),
        @Email				varchar(100)
	)

AS


    -- @PaymentDetailsID int = NULL,    -- Above input parameter not used ???

    SET NOCOUNT ON

	DECLARE @AS_Transaction_Payments_ID	int,
			@AS_Transactions_ID	int,
			@Transaction_Number varchar(19)
	
	INSERT AS_Transaction_Payments
    	(	
    		AS_Transactions_ID,
    		Sys_AW_Payment_Methods_ID, 
    		Slu_AS_Card_Institutions_ID,
    		Payor_Name,
    		Card_Expiry_Date,
    		Card_Number,
    		Authorisation_Number,
    		Amount,
    		[User_ID],
    		AW_User_Companies_ID,
    		Date_Captured
    	)
	VALUES
    	(
    		@PaymentID,
    		@MethodID,
    		@InstitutionID,
    		@PayorName,
    		@CardExpiryDate,
    		@CardNo,
    		@AuthorisationNo,
    		@Amount,
    		@UserID,
    		@CompanyID,
    		@Date
    	)
    	
    SELECT @AS_Transaction_Payments_ID = Scope_Identity()
    
	IF (ISNULL(@IPay_ID,'') <> '' And (@MethodID = 14))
	BEGIN
		--SELECT @Transaction_Number = Transaction_Number
		--FROM AS_Transactions
		--WHERE AS_Transactions_ID = @PaymentID 
	
		--SELECT @AS_Transactions_ID = AS_Transactions_ID
		--FROM AS_Transactions
		--WHERE Sys_AW_Transaction_Types_ID = 3
		--AND Transaction_Number = @Transaction_Number
	
		Update AS_Transaction_Payments_IPay
		Set --AS_Transactions_ID = @AS_Transactions_ID,
			AS_Transaction_Payments_ID = @AS_Transaction_Payments_ID,
			IPay_Status = 1
		Where IPay_ID = @IPay_ID
		AND IPay_Action IN ('PAY SUC' ,'PAYDONE', 'DAYEND_1')
		--AND IPay_Status <> 1
	END
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Payments_IPay_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Payments_IPay_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   : sp_AS_Transaction_Payments_IPay_Insert
--Purpose       : Inserts POS i-Pay Payment Details
--Functionality : Tables: AS_Transaction_Payments
--Parameters    : 
--Date          : 2018-03-20
--Authors       : RL
--Version       :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Payments_IPay_Insert]
	(					
		@Ipay_Action					[varchar](10),
		@AS_Transactions_ID				[int],
		@AS_Transaction_Payments_ID		[int],
		@IPay_ID						[varchar](50),
		@IPay_Tran_Ref					[varchar](50),
		@IPay_Bank_Ref					[varchar](50),
		@IPay_URL						[varchar](250),
		@IPay_Status					int, --0 Still awaiting payment, 1 Paid, 2 Other
		@Amount							money,
		@Cell_No						[varchar](20),
		@Email							[varchar](100),	
		@Status_Code					[varchar](50),
		@Status_Description				[varchar](250),
		@HTTPStatus						[varchar] (20),
		@User_ID						[int],
		@CompanyID						[int]
	)

AS

	DECLARE	@Done	int,
			@PaymentID int,
			@CustomerID int,
			@AccountID int,
			@TransactionNumber varchar(19),
			@TotalAmount money,
			@PaymentAmount money,
			@CustomerReference varchar(15),
			@TransactionTypeID int,
			@StoreID int,
			@WorkstationID int,
			@TillID int,
			@CashierID int,
			@RepID int,
			@CurrencyID int,
			@DateCaptured datetime,
			@SourceTransactionID int
	
	SELECT @Done = 0
	
	IF @IPay_Status = 99
	BEGIN
		UPDATE AS_Transaction_Payments_IPay
		SET AS_Transactions_ID = @AS_Transactions_ID
		WHERE IPay_ID = @IPay_ID
		AND IPay_Action = 'PAY SUC'
		
		SELECT @Done = 1
	END
	
	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_1'
		BEGIN
	--Select @AS_Transactions_ID As '@AS_Transactions_ID'	
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				'PAYDONE',
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			

			SELECT  @PaymentAmount = Payment_Amount,
					@TotalAmount = Total_Amount,
					@CustomerID = AC_Customers_ID,
					@TransactionTypeID = Sys_AW_Transaction_Types_ID,
					@CustomerReference = Customer_Reference,
					@TillID = Lup_AS_Tills_ID,
					@CashierID = Lup_AS_Cashiers_ID,
					@RepID = LUP_AS_Reps_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @AS_Transactions_ID

			SELECT @DateCaptured = GETDATE()
			
			IF @PaymentAmount = 0
			BEGIN
				Exec sp_AS_POS_Transaction_Payment_Insert
					@PaymentID Output,
					@CustomerID,
					@AccountID,
					@TransactionNumber,
					@Amount,
					@Amount,
					@CustomerReference,
					@TransactionTypeID,
					@StoreID,
					NULL,--@WorkstationID,
					@TillID,
					@CashierID,
					@RepID,
					@CurrencyID,
					@DateCaptured,
					@User_ID,
					@CompanyID,
					@AS_Transactions_ID
			END
			ELSE
			BEGIN
				Exec sp_AS_POS_Transaction_Payment_Insert
					@PaymentID Output,
					@CustomerID,
					@AccountID,
					@TransactionNumber,
					@Amount,
					0,
					@CustomerReference,
					@TransactionTypeID,
					@StoreID,
					NULL,--@WorkstationID,
					@TillID,
					@CashierID,
					@RepID,
					99,
					@DateCaptured,
					@User_ID,
					@CompanyID,
					@AS_Transactions_ID			
			END
				 
			SET @TotalAmount = @Amount * -1
 
			Exec sp_AS_POS_Transaction_Payment_Detail_Insert
				@TotalAmount,--@Amount,	
				'',--@PayorName,
				'',--@CardExpiryDate,
				'',--@CardNo,
				'',--@AuthorisationNo,
				14,--@MethodID,
				1,--@InstitutionID,
				@User_ID,
				@CompanyID,
				0,--@PaymentDetailsID,
				@PaymentID,--@PaymentID
				@DateCaptured,
				@IPay_ID,
				'',--@IPay_Tran_Ref,
				'',--@IPay_Bank_Ref,
				1,--@IPay_Status
				'',--@Cell_No,
				''--@Email

			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
				Status_Code = @Status_Code,
				Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'

			SELECT @Done = 1		
		END
	END
	
	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_2'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				@Ipay_Action,
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			IF @Status_Code NOT IN ('Created', 'Waiting', 'Cancelled')
			BEGIN
				UPDATE AS_Transaction_Payments_IPay
				SET IPay_Status = 1,
					Status_Code = @Status_Code,
					Status_Description = @Status_Description
				WHERE IPay_ID = @IPay_ID
				AND IPay_Action = 'PAY SUC'
			END
			
			SELECT @Done = 1		
		END		
	END

	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'DAYEND_3'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				'PAYDONE',
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
				Status_Code = @Status_Code,
				Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'
		
			SELECT @Done = 1		
		END		
	END

	IF @Done = 0
	BEGIN
		IF @Ipay_Action = 'PAYDONE'
		BEGIN
			INSERT INTO AS_Transaction_Payments_IPay
			(
				Ipay_Action,
				AS_Transactions_ID,
				AS_Transaction_Payments_ID,
				IPay_ID,
				IPay_Tran_Ref,
				IPay_Bank_Ref,
				IPay_URL,
				IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
				Amount,
				Cell_No,
				Email,
				Status_Code,
				Status_Description,
				HTTPStatus,
				[User_ID],
				AW_User_Companies_ID
			)
			VALUES
			(
				@Ipay_Action,
				@AS_Transactions_ID,
				@AS_Transaction_Payments_ID,
				@IPay_ID,
				@IPay_Tran_Ref,
				@IPay_Bank_Ref,
				@IPay_URL,
				@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
				@Amount,
				@Cell_No,
				@Email,	
				@Status_Code,
				@Status_Description,
				@HTTPStatus,
				@User_ID,
				@CompanyID
			)			
			
			--Used to pole unpaid transactions on day-end
			UPDATE AS_Transaction_Payments_IPay
			SET IPay_Status = 1,
					Status_Code = @Status_Code,
					Status_Description = @Status_Description
			WHERE IPay_ID = @IPay_ID
			AND IPay_Action = 'PAY SUC'

			SELECT @Done = 1		
		END
	END
	
	IF @Done = 0 
	BEGIN
		INSERT INTO AS_Transaction_Payments_IPay
		(
			Ipay_Action,
			AS_Transactions_ID,
			AS_Transaction_Payments_ID,
			IPay_ID,
			IPay_Tran_Ref,
			IPay_Bank_Ref,
			IPay_URL,
			IPay_Status, --0 Still awaiting payment Confirmation, 1 Paid, 2 Other
			Amount,
			Cell_No,
			Email,
			Status_Code,
			Status_Description,
			HTTPStatus,
			[User_ID],
			AW_User_Companies_ID
		)
		VALUES
		(
			@Ipay_Action,
			@AS_Transactions_ID,
			@AS_Transaction_Payments_ID,
			@IPay_ID,
			@IPay_Tran_Ref,
			@IPay_Bank_Ref,
			@IPay_URL,
			@IPay_Status, --0 Still awaiting payment, 1 Paid, 2 Other
			@Amount,
			@Cell_No,
			@Email,	
			@Status_Code,
			@Status_Description,
			@HTTPStatus,
			@User_ID,
			@CompanyID
		)
	END	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Select_User_ID]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Select_User_ID]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_User_ID
--Purpose       :Select POS Login User From ID
--Date          :2006/04/30
--Authors       :TB
--MODS:         :
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_POS_Select_User_ID]
    (
        @UserID int
    )
AS

SET NOCOUNT ON

    SELECT UserName,
          [Password],
           Surname + ISNULL(', ' + Firstname, '') AS [Fullname],
           ISNULL(User_Email,'') AS [User Email]
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Login]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Login]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Login
--Purpose       :Select POS Login User
--Parameters    :
--Date          :2002/01/12
--Authors       :TB
--MODS:         :16/07/03 - Changed user Fullname to Firstname/Surname
--2004.4.8      :Added check validation on ACTIVE users only
--V6.4		RL	:2018-02-14 - Return User Email
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Login]
    (
        @Username varchar(50) = '',
        @Password varchar(50) = '',
        @CompanyID int = 0,
        @TillID int =0
    )

AS

SET NOCOUNT ON

    SELECT DISTINCT 
        u.UserName, 
        u.[Password], 
        cu.AW_User_Companies_ID, 
        ut.Lup_AS_Tills_ID, 
        u.AW_Users_ID as [ID],
        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') as [Fullname],
        ISNULL(u.User_Email,'') AS [User Email]
    FROM AW_Users u 
        INNER JOIN AW_Users_Tills ut
            ON u.AW_Users_ID = ut.AW_Users_ID 
        INNER JOIN AW_Company_Users cu
            ON u.AW_Users_ID = cu.AW_Users_ID 
    WHERE u.UserName = @UserName AND
          u.[Password] = @Password AND
          cu.AW_User_Companies_ID = @CompanyID AND
          ut.Lup_AS_Tills_ID = @TillID AND
          u.Slu_AW_Active_ID = 1


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Update
--Purpose       :Updates address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-07-09
--Authors       :RL
--Mods
--V6.3	RL	2017-02-28	:Don't remove address details
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Update]
    (    	    	
    	@AS_Transactions_Address_Detail_ID	int,
    	@Inv_Customer_Name					varchar(100),	--1
		@Inv_Address1						varchar(40),	--2
		@Inv_Address2						varchar(40),	--3
		@Inv_City							varchar(30),	--4
		@Inv_Code							varchar(10),	--5
		@Inv_Tax_Number						varchar(16),	--6
		@Cell_No							varchar(16),	--7
		@Email								varchar(100),	--8
		@Delivery_Address					varchar(40),
		@Delivery_Suburb					varchar(40),
		@Delivery_City						varchar(30),
		@Delivery_Post_Code					varchar(10),
		@User_ID							int,
		@AC_Customers_ID					int,
		@AS_Transactions_ID					int,
		@Company_ID							int		
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
    	@AW_YesNo_Delivery_Address	int,
    	@AW_YesNo_Invoice			int,
    	@Exact_Record				int,
    	@Other_Record				int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
	SET @Exact_Record = 0
	SET @Other_Record = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Cell_No = LTRIM(RTRIM(ISNULL(@Cell_No,'')))
	SET @Email = LTRIM(RTRIM(ISNULL(@Email,'')))	
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))

	IF (
		@Inv_Customer_Name <> '' Or
		@Inv_Address1 <> '' Or
		@Inv_Address2 <> '' Or
		@Inv_Code <> '' Or
		@Inv_City <> '' Or
		@Inv_Tax_Number <> '' Or
		@Cell_No <> '' Or
		@Email <> ''
		)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	SELECT @Other_Record = COUNT(*)
	FROM AS_Transactions_Address ta
		INNER JOIN AS_Transactions_Address_Detail ad
			ON ta.AS_Transactions_Address_Detail_ID = ad.AS_Transactions_Address_Detail_ID
	WHERE ta.AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	AND AS_Transactions_ID <> @AS_Transactions_ID	
	
	--IF (@AW_YesNo_Invoice = 0 AND @AW_YesNo_Delivery_Address = 0)
	--BEGIN
	--	DELETE FROM AS_Transactions_Address_Detail WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--	DELETE FROM AS_Transactions_Address WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--END
	--ELSE
	--BEGIN
	IF (@AS_Transactions_Address_Detail_ID = 0) OR (@Other_Record > 0)
	BEGIN	
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				Cell_No,
				Email, 
				Delivery_Address, 
				Delivery_Suburb, 
				Delivery_City, 
				Delivery_Post_Code,
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID,
				AW_YesNo_Delivery_Address,
				AW_YesNo_Invoice
			)
		VALUES
			(
				@AC_Customers_ID,
				@Inv_Customer_Name,
				@Inv_Address1,
				@Inv_Address2,
				@Inv_Code,
				@Inv_City,
				@Inv_Tax_Number,
				@Cell_No,
				@Email,
				@Delivery_Address,
				@Delivery_Suburb,
				@Delivery_City,
				@Delivery_Post_Code,
				GETDATE(),
				@User_ID,
    			@Company_ID,
    			@AW_YesNo_Delivery_Address,
    			@AW_YesNo_Invoice
			)
			
		SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
		
		IF @Other_Record = 0
		BEGIN
			INSERT INTO AS_Transactions_Address
				(
					AS_Transactions_ID, 
					AS_Transactions_Address_Detail_ID, 
					Date_Captured, 
					User_ID, 
					AW_User_Companies_ID
				)
			VALUES
				(
					@AS_Transactions_ID,
					@AS_Transactions_Address_Detail_ID,
					GETDATE(),
					@User_ID,
    				@Company_ID
    			)
    	END
    	ELSE
    	BEGIN
    		UPDATE AS_Transactions_Address
    		SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
    		WHERE AS_Transactions_ID = @AS_Transactions_ID
    	END
	END
	ELSE
	BEGIN	 
		UPDATE AS_Transactions_Address_Detail
		SET
			Customer_Name = @Inv_Customer_Name,
			Inv_Address1 = @Inv_Address1,
			Inv_Address2 = @Inv_Address2,
			Inv_Code = @Inv_Code,
			Inv_City = @Inv_City,
			Tax_Number = @Inv_Tax_Number,
			Cell_No = @Cell_No,
			Email = @Email,			
			Delivery_Address = @Delivery_Address,
			Delivery_Suburb = @Delivery_Suburb,
			Delivery_City = @Delivery_City,
			Delivery_Post_Code = @Delivery_Post_Code
		WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
			  
	END
SET NOCOUNT ON
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Stored Procedure


-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Insert
--Purpose       :Keeps a record of address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-01-02
--Authors       :RL
--Mod			:RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID
--V6.3	RL	2017-02-28	:Changed so that each document will have its own link in the address details table
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Insert]
    (	@AC_Customers_ID					int,	--RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID	
		@Company_ID							int,			--In POS code, Customer is sent through first
    	@AS_Transactions_ID					int,
    	@Inv_Customer_Name					varchar(100),
		@Inv_Address1						varchar(40),
		@Inv_Address2						varchar(40),
		@Inv_City							varchar(30),
		@Inv_Code							varchar(10),
		@Inv_Tax_Number						varchar(16),
		@Cell_No							varchar(16),
		@Email								varchar(100),
		@Delivery_Address					varchar(40),
		@Delivery_Suburb					varchar(40),
		@Delivery_City						varchar(30),
		@Delivery_Post_Code					varchar(10),
		@User_ID							int
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
		@AS_Transactions_Address_Detail_ID	int,
    	@AW_YesNo_Delivery_Address int,
    	@AW_YesNo_Invoice int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
	SET @AS_Transactions_Address_Detail_ID = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))
	SET @Cell_No = LTRIM(RTRIM(ISNULL(@Cell_No,'')))
	SET @Email = LTRIM(RTRIM(ISNULL(@Email,'')))

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	-- Check if values changed from customer
	DECLARE 
		@Inv_Customer_Name_DB					varchar(100),
		@Inv_Address1_DB						varchar(40),
		@Inv_Address2_DB						varchar(40),
		@Inv_City_DB							varchar(30),
		@Inv_Code_DB							varchar(10),
		@Inv_Tax_Number_DB						varchar(16),
		@Cell_No_DB								varchar(16),
		@Email_DB								varchar(100),
		@WhichAddress							tinyint = 0,
		@WhichName								tinyint = 0;
	
	SELECT @WhichAddress = ISNULL(Control_Index, 0)
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
		Control_Name = 'optPOSPrintAddress' AND
		Control_Value = 'True'

	--> Get Which Name Format To Use
	SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM Sys_AW_Options
	WHERE Control_Index = 0 AND
	Control_Type = 'CheckBox' AND
	Control_Name = 'chkPOSPrintTradeName'
	
	IF (@WhichAddress = 0)
	BEGIN
		SELECT 
			@Inv_Customer_Name_DB = (CASE WHEN @WhichName = 1 THEN 
									  (CASE 
										WHEN ISNULL(Initials,'') = ''  
										THEN    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname))    
											ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										ELSE    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))    
											ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										END)
									ELSE
									  CASE WHEN ISNULL(Initials,'') = ''   
										THEN LTRIM(RTRIM(Surname))   
										ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
									  END
									END),
			@Inv_Address1_DB = Post_Box,						
			@Inv_Address2_DB = Post_Office,						
			@Inv_City_DB = City,							
			@Inv_Code_DB = Post_Code,							
			@Inv_Tax_Number_DB = Tax_Number,						
			@Cell_No_DB = Cell_No						
		FROM
			AC_Customers		
		WHERE 
			AC_Customers_ID = @AC_Customers_ID 
	END
	ELSE 
	BEGIN
		SELECT 
			@Inv_Customer_Name_DB = (CASE WHEN @WhichName = 1 THEN 
									  (CASE 
										WHEN ISNULL(Initials,'') = ''  
										THEN    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname))    
											ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										ELSE    
											CASE WHEN ISNULL(Firstnames,'') = ''    
											THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))    
											ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))    
											END   
										END)
									ELSE
									  CASE WHEN ISNULL(Initials,'') = ''   
										THEN LTRIM(RTRIM(Surname))   
										ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
									  END 
									END),
			@Inv_Address1_DB = Street_Address,						
			@Inv_Address2_DB = Suburb,						
			@Inv_City_DB = City,							
			@Inv_Code_DB = Street_Post_Code,							
			@Inv_Tax_Number_DB = Tax_Number,						
			@Cell_No_DB = Cell_No						
		FROM
			AC_Customers		
		WHERE 
			AC_Customers_ID = @AC_Customers_ID 
	END 
	
	IF 
	(
		@Inv_Customer_Name <> @Inv_Customer_Name_DB Or
		@Inv_Address1 <> @Inv_Address1_DB Or
		@Inv_Address2 <> @Inv_Address2_DB Or
		@Inv_Code <> @Inv_Code_DB Or
		@Inv_City <> @Inv_City_DB Or
		@Inv_Tax_Number <> @Inv_Tax_Number_DB Or
		@Cell_No <> @Cell_No_DB
	)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END
	
	
		 
	--V6.3 Each document will have its own link in the address details table
	--SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID
	--FROM AS_Transactions_Address_Detail
	--WHERE AC_Customers_ID = @AC_Customers_ID AND
	--	  Customer_Name = @Inv_Customer_Name AND
	--	  Inv_Address1 = @Inv_Address1 AND
	--	  Inv_Address2 = @Inv_Address2 AND
	--	  Inv_Code = @Inv_Code AND
	--	  Inv_City = @Inv_City AND
	--	  Tax_Number = @Inv_Tax_Number AND
	--	  Delivery_Address = @Delivery_Address AND
	--	  Delivery_Suburb = @Delivery_Suburb AND
	--	  Delivery_City = @Delivery_City AND
	--	  Delivery_Post_Code = @Delivery_Post_Code

	--IF @AS_Transactions_Address_Detail_ID = 0
	--BEGIN
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				Cell_No,
				Email, 
				Delivery_Address, 
				Delivery_Suburb, 
				Delivery_City, 
				Delivery_Post_Code, 
				Date_Captured,
				User_ID, 
				AW_User_Companies_ID,
				AW_YesNo_Delivery_Address,
				AW_YesNo_Invoice
			)
		VALUES
			(
				@AC_Customers_ID,
				@Inv_Customer_Name,
				@Inv_Address1,
				@Inv_Address2,
				@Inv_Code,
				@Inv_City,
				@Inv_Tax_Number,
				@Cell_No,
				@Email,
				@Delivery_Address,
				@Delivery_Suburb,
				@Delivery_City,
				@Delivery_Post_Code,
				GETDATE(),
				@User_ID,
    			@Company_ID,
    			@AW_YesNo_Delivery_Address,
    			@AW_YesNo_Invoice
			)
			
		SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
		
		INSERT INTO AS_Transactions_Address
			(
				AS_Transactions_ID, 
				AS_Transactions_Address_Detail_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID
			)
		VALUES
			(
				@AS_Transactions_ID,
				@AS_Transactions_Address_Detail_ID,
				GETDATE(),
				@User_ID,
    			@Company_ID
			)	
	--END
	--ELSE
	--BEGIN
	--	INSERT INTO AS_Transactions_Address
	--		(
	--			AS_Transactions_ID, 
	--			AS_Transactions_Address_Detail_ID, 
	--			Date_Captured, 
	--			User_ID, 
	--			AW_User_Companies_ID
	--		)
	--	VALUES
	--		(
	--			@AS_Transactions_ID,
	--			@AS_Transactions_Address_Detail_ID,
	--			GETDATE(),
	--			@User_ID,
 --   			@Company_ID
	--		)		
	--END
SET NOCOUNT OFF	

GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Select
--Purpose       :Select address details used on Invoices
--Functionality :Select address details used on Invoices
--Date          :2013-01-02
--Authors       :RL
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Select]
    (    	    	
    	@AS_Transactions_ID int
    )
AS 

	SET NOCOUNT ON

	IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions_Address
			WHERE AS_Transactions_ID = @AS_Transactions_ID
		)
	BEGIN
		SELECT AS_Transactions_ID,
			   Customer_Name AS 'Customer_Name',
			   Inv_Address1 AS 'Inv_Address1',
			   Inv_Address2 AS 'Inv_Address2',
			   Inv_City AS 'Inv_City',
			   Inv_Code AS 'Inv_Code',		
			   Tax_Number As 'Tax_Number',	   
			   Cell_No AS 'Cell_No',
			   Email AS 'Email',
			   Delivery_Address AS 'Delivery_Address',
			   Delivery_Suburb AS 'Delivery_Suburb',
			   Delivery_City AS 'Delivery_City',
			   Delivery_Post_Code AS 'Delivery_Post_Code'
		FROM AS_Transactions_Address_Detail d
			INNER JOIN AS_Transactions_Address a 
				ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID	
		WHERE a.AS_Transactions_ID = @AS_Transactions_ID
	END
	ELSE
	BEGIN
		SELECT 
			0 AS 'AS_Transactions_ID',
			'' AS 'Customer_Name',
			'' AS 'Inv_Address1',
			'' AS 'Inv_Address2',
			'' AS 'Inv_City',
			'' AS 'Inv_Code',
			'' AS 'Tax_Number',			
			'' AS 'Cell_No',
			'' AS 'Email',
			'' AS 'Delivery_Address',
			'' AS 'Delivery_Suburb',
			'' AS 'Delivery_City',
			'' AS 'Delivery_Post_Code'
			
	END
	
SET NOCOUNT OFF
GO	
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Delivery_Address_Hist]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Delivery_Address_Hist]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Delivery_Address_Hist
--Purpose       :Select address details used by customer
--Functionality :Select address details used by customer
--Date          :2013-01-02
--Authors       :RL
--V6.3	RL	2017-03-07	:Select Record per transaction
--V6.4	RL	2018-03-27	:Added Cellphone and email
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
    (    	    	
    	@AC_Customers_ID int
    )
AS 

	DECLARE @sql varchar(8000)
		
	SET @sql = ' ' 
	SET @sql = @sql + ' DECLARE @WhichAddress tinyint, '
	SET @sql = @sql + ' @WhichName tinyint '

	SET @sql = @sql + ' SET @WhichAddress = 0 '

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SET @sql = @sql + ' SELECT @WhichAddress = ISNULL(Control_Index, 0) '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Type = ''OptionButton'' AND '
	SET @sql = @sql + ' Control_Name = ''optPOSPrintAddress'' AND '
	SET @sql = @sql + ' Control_Value = ''True'' '

	SET @sql = @sql + ' SELECT TOP 1 @WhichName = ISNULL(Control_Value, ''0'') '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Index = 0 AND '
	SET @sql = @sql + ' Control_Type = ''CheckBox'' AND '
	SET @sql = @sql + ' Control_Name = ''chkPOSPrintTradeName'' '


	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + ' 	ISNULL(ad.Customer_Name,'''') AS [Customer_Name], '
	SET @sql = @sql + ' 	tt.[Description] As [Tran_Type], '
	SET @sql = @sql + ' 	th.Transaction_Date AS [Transaction_Date], '
	SET @sql = @sql + ' 	th.Transaction_Number As [Transaction_Number], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Address1,'''') AS [Inv_Address1], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Address2,'''') AS [Inv_Address2], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_City,'''') AS [Inv_City], '
	SET @sql = @sql + ' 	ISNULL(ad.Inv_Code,'''') AS [Inv_Code], '
	SET @sql = @sql + ' 	ISNULL(ad.Tax_Number,'''') AS [Tax_Number], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(ad.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(ad.Email,'''') AS [Email], '	
	
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Address,'''') AS [Delivery_Address], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Suburb,'''') AS [Delivery_Suburb], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_City,'''') AS [Delivery_City], '
	SET @sql = @sql + ' 	ISNULL(ad.Delivery_Post_Code,'''') AS [Delivery_Post_Code], '
	SET @sql = @sql + ' 	ad.AS_Transactions_Address_Detail_ID As [ID], '
	SET @sql = @sql + ' 	th.AS_Transactions_ID As [AS_Transactions_ID] '	
	SET @sql = @sql + ' FROM AS_Transactions_Address_Detail	ad '
	SET @sql = @sql + ' 	INNER JOIN AS_Transactions_Address ah '
	SET @sql = @sql + ' 		ON ad.AS_Transactions_Address_Detail_ID = ah.AS_Transactions_Address_Detail_ID '
	SET @sql = @sql + ' 	INNER JOIN AS_Transactions th '
	SET @sql = @sql + ' 		ON ah.AS_Transactions_ID = th.AS_Transactions_ID '
	SET @sql = @sql + ' 	INNER JOIN Sys_AW_Transaction_Types tt '
	SET @sql = @sql + ' 		on th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHERE ad.AC_Customers_ID = ' + CONVERT(varchar(20), @AC_Customers_ID)
	SET @sql = @sql + ' AND th.Sys_AW_Transaction_Types_ID IN (1, 2, 3, 4, 7, 13, 16, 17, 21, 22, 33, 34, 35) '
	SET @sql = @sql + ' UNION '
	SET @sql = @sql + ' SELECT '
		
	SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + ' 	CASE WHEN ISNULL(cc.Initials,'''') = '''' '
	SET @sql = @sql + ' 	THEN '
	SET @sql = @sql + ' 		CASE WHEN ISNULL(cc.Firstnames,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) '
	SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(cc.Surname)) + '' / '' + LTRIM(RTRIM(cc.Firstnames)) '
	SET @sql = @sql + ' 		END '
	SET @sql = @sql + ' 	ELSE '
	SET @sql = @sql + ' 		CASE WHEN ISNULL(cc.Firstnames,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) '
	SET @sql = @sql + ' 			ELSE LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) + '' / '' + LTRIM(RTRIM(cc.Firstnames)) '
	SET @sql = @sql + ' 		END '
	SET @sql = @sql + ' 	END '
	SET @sql = @sql + ' ELSE '
	SET @sql = @sql + ' 	CASE WHEN ISNULL(cc.Initials,'''') = '''' '
	SET @sql = @sql + ' 		THEN LTRIM(RTRIM(cc.Surname)) '
	SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(cc.Surname)) + '', '' + LTRIM(RTRIM(cc.Initials)) '
	SET @sql = @sql + ' 	END '
	SET @sql = @sql + ' END AS [Customer_Name], '
		
	SET @sql = @sql + '		tt.[Description] As [Tran_Type], '
	SET @sql = @sql + '		th.Transaction_Date AS [Transaction_Date], '
	SET @sql = @sql + '		th.Transaction_Number As [Transaction_Number], '
	
	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Box, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Street_Address, '''') '
	SET @sql = @sql + ' END AS [Inv_Address1], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Office, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Suburb, '''') '
	SET @sql = @sql + ' END AS [Inv_Address2], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.City, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.City, '''') '
	SET @sql = @sql + ' END AS [Inv_City], '

	SET @sql = @sql + ' CASE WHEN @WhichAddress = 0 '
	SET @sql = @sql + ' THEN '
	SET @sql = @sql + '		ISNULL(cc.Post_Code, '''') '
	SET @sql = @sql + '	ELSE '
	SET @sql = @sql + '		ISNULL(cc.Street_Post_Code, '''') '
	SET @sql = @sql + ' END AS [Inv_Code], '
		
	SET @sql = @sql + '		ISNULL(cc.Tax_Number,'''') AS [Tax_Number], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(cc.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(cc.Orders_URL,'''') AS [Email], '	
	
	SET @sql = @sql + '		ISNULL(cc.Delivery_Address,'''') AS [Delivery_Address], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_Suburb,'''') AS [Delivery_Suburb], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_City,'''') AS [Delivery_City], '
	SET @sql = @sql + '		ISNULL(cc.Delivery_Post_Code,'''') AS [Delivery_Post_Code], '
	SET @sql = @sql + '		0 As [ID], '
	SET @sql = @sql + ' 	th.AS_Transactions_ID As [AS_Transactions_ID] '		
	SET @sql = @sql + ' FROM AS_Transactions th '
	SET @sql = @sql + ' 	INNER JOIN AC_Customers cc '
	SET @sql = @sql + ' 		ON th.AC_Customers_ID = cc.AC_Customers_ID '
	SET @sql = @sql + ' 	INNER JOIN Sys_AW_Transaction_Types tt '
	SET @sql = @sql + ' 		on th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' WHERE th.AC_Customers_ID = ' + CONVERT(varchar(20), @AC_Customers_ID)
	SET @sql = @sql + ' AND th.Sys_AW_Transaction_Types_ID IN (1, 2, 3, 4, 7, 13, 16, 17, 21, 22, 33, 34, 35) '
	SET @sql = @sql + ' AND th.AS_Transactions_ID NOT IN '
	SET @sql = @sql + ' 							( '
	SET @sql = @sql + ' 								SELECT AS_Transactions_ID '
	SET @sql = @sql + ' 								FROM AS_Transactions_Address '
	SET @sql = @sql + ' 							) '
	SET @sql = @sql + ' ORDER BY Transaction_Date DESC, Transaction_Number '

EXEC (@sql)
--Select @sql
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Customer_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Customer_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/15
--Authors       :TB
--MODS          :24/07/02 - Added Sys_AW_Transactions_Types_ID's 21 and 22 to
--              :           @Choice=17 (Customer Catalog cboCustTrans)
--              :04/08/03 - Added Choice 18 & 19, Transaction Types - Quotes, 
--              :           Jobcards, Proformas and Users for Deactivate Transactions
--              :06/08/03 - Added Choice 20 Active for Deactivate Transactions
--              :09/08/03 - Added Choice 21 ALL Transaction Types - Sales Chronolgy
--              :20/12/03 - Added Choice 22 Use Assets in Customer Catalog
--              :04/01/04 - Added Choice 23 to 48 for Credit Manager
--              :05/07/04 - Added Choice 49 for Lup_AC_Customer_Groups
--              :05/01/05 - Added Choice 50 for Customers Payments History
--2004.2.7      :10/03/06 - Added Choice = 51 for Customer E-Mail addresses
--2004.3.7      :25/07/07 - Added Choice = 52 for Customer Cost+Plus Category
--2004.3.8      :02/12/07 - Added ORDER BY for Reps, Countries, Customer Type,
--              :           Sales Areas, and Customer Groups
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.3      :17/03/09 - Added Option = 53 for Statement Messages - Active only
--2004.4.7      :22/08/09 - Added new Select Stock Transfer TranType = 23 where required
--2004.5.0      :16/11/10 - Change alias in Choice 51 from [EMail] to [E-Mail] for Periodic Billing
--              :21/01/11 - Added Option = 54 for Periodic Billing
--V6.2	RL	2015-05-18	:Added Option 56 - Customer Consignment Stock Transaction Types
--V6.2	RL	2015-06-10	:Added Customer Consignment Transactions to options 17 and 21
--V6.4	RL	2018-03-27	:Added option 58 Added AS_Transactions_Address_Detail Email
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Lups]
    (
       	@Choice int,
    	@CompanyID int
    )
AS

BEGIN
    IF @Choice = 1	--'Title'
        SELECT Slu_AW_Titles_ID AS [ID], [Description] 
        FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE

    IF @Choice = 2	--'Language'
      	SELECT Slu_AW_Languages_ID AS [ID],  [Description]  
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE

    IF @Choice = 3	--'Yes No'
      	SELECT Slu_AW_YesNo_ID AS [ID],  [Description]  	
        FROM Slu_AW_YesNo

    ELSE
    IF @Choice = 4	--'Sales Discount'
      	SELECT Lup_AC_Discount_Categories_ID AS [ID],  [Description] 
        FROM Lup_AC_Discount_Categories
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 5	--'Credit Terms'
      	SELECT Slu_AW_Credit_Terms_ID AS [ID],  [Description] 	
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Choice = 6	--'Terms Of Sale        'Credit Term Types'
      	SELECT Sys_AC_Credit_Term_Types_ID AS [ID], [Description] 
        FROM Sys_AC_Credit_Term_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 7	--'Account Types'
      	SELECT Sys_AC_Account_Types_ID AS [ID], [Description] 
        FROM Sys_AC_Account_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 8 	--'Reps  **'
      	SELECT Lup_AS_Reps_ID AS [ID], Description 
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 9	--'Active'
      	SELECT Slu_AW_Active_ID AS [ID], Description 
        FROM Slu_AW_Active 
        ORDER BY [Description]

    ELSE
    IF @Choice = 10	--'Account Status'
      	SELECT Sys_AC_Account_Status_ID AS [ID], Description 
        FROM Sys_AC_Account_Status  
        ORDER BY [Description]

    ELSE
    IF @Choice = 11	--'Tax Code'
      	SELECT Sys_AW_Tax_Codes_ID AS [ID], Description, Tax_Rate AS [Tax Rate] 
        FROM Sys_AW_Tax_Codes 

    ELSE
    IF @Choice = 12	--'Countries **'
        SELECT Slu_AW_Countries_ID AS [ID], Description 
        FROM Slu_AW_Countries
        ORDER BY [Description]

    ELSE
    IF @Choice = 13	--'Actor2'    '(Customer Tasks)
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [Actor2]
        FROM AW_Users 
        WHERE AW_Users_ID > 1
        ORDER BY [Actor2]

    ELSE
    IF @Choice = 14	--'Customer Type **'
      	SELECT Lup_AC_Customer_Types_ID as [ID] , Description
        FROM Lup_AC_Customer_Types 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 15 --Transaction Types
        SELECT Sys_AW_Transaction_Types_ID as [ID], Description
        FROM Sys_AW_Transaction_Types 
        WHERE Sys_AW_Transaction_Types_ID <= 4

    ELSE
    IF @Choice = 16 --'Sales Areas **'
      	SELECT Lup_AC_Sales_Areas_ID as [ID], Description
        FROM Lup_AC_Sales_Areas 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 17 --Transaction Types - ALL
        SELECT Sys_AW_Transaction_Types_ID as [ID],
               [Description]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or 
              Sys_AW_Transaction_Types_ID = 4 or 
              Sys_AW_Transaction_Types_ID = 5 or 
              Sys_AW_Transaction_Types_ID = 7 or 
              Sys_AW_Transaction_Types_ID = 13 or
              Sys_AW_Transaction_Types_ID = 15 or 
              Sys_AW_Transaction_Types_ID = 16 or 
        	  Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or 
        	  Sys_AW_Transaction_Types_ID = 22 or
              Sys_AW_Transaction_Types_ID = 23 or
              Sys_AW_Transaction_Types_ID = 33 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 34 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 35		--V6.2 Consignment Transactions
        ORDER BY Description

    ELSE
    IF @Choice = 18 --Transaction Types - Quotes, Jobs, Proformas and Sales Orders only
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or
              Sys_AW_Transaction_Types_ID = 13 or
              Sys_AW_Transaction_Types_ID = 16 or
              Sys_AW_Transaction_Types_ID = 23

    ELSE
    IF @Choice = 19	--'Users'
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]

    ELSE
    IF @Choice = 20	--'Active' for Deactivate Transactions
      	SELECT Slu_AW_Active_ID AS [ID],
               [Description] AS [Active] 
        FROM Slu_AW_Active 

    ELSE
    IF @Choice = 21 --Transaction Types - ALL (Manager Console - Sales Chronology)
        SELECT Sys_AW_Transaction_Types_ID as [ID],
               [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 1 or
              Sys_AW_Transaction_Types_ID = 2 or 
              Sys_AW_Transaction_Types_ID = 3 or 
              Sys_AW_Transaction_Types_ID = 4 or 
              Sys_AW_Transaction_Types_ID = 5 or 
              Sys_AW_Transaction_Types_ID = 7 or
              Sys_AW_Transaction_Types_ID = 13 or 
              Sys_AW_Transaction_Types_ID = 15 or 
              Sys_AW_Transaction_Types_ID = 16 or 
        	  Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or 
        	  Sys_AW_Transaction_Types_ID = 22 or
              Sys_AW_Transaction_Types_ID = 23 or
              Sys_AW_Transaction_Types_ID = 33 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 34 or	--V6.2 Consignment Transactions
              Sys_AW_Transaction_Types_ID = 35		--V6.2 Consignment Transactions

    ELSE
    IF @Choice = 22	--'Active' for Use Assets
      	SELECT Sys_AC_Use_Assets_ID AS [ID],
               [Description] AS [Description] 
        FROM Sys_AC_Use_Assets 

	ELSE 
	IF @Choice = 23    --Controllers
		SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [Description]
		FROM AW_Users
        WHERE IsController = 1
        ORDER BY [Description]

    ELSE
    IF @Choice = 24    --'Delivery Methods'
      	SELECT Sys_AW_Delivery_Methods_ID as [ID] , [Description]
        FROM Sys_AW_Delivery_Methods 

    ELSE
    IF @Choice = 25	--'Pricipal Contact Method'
      	SELECT Sys_AW_Delivery_Methods_ID as [ID] , [Description]
        FROM Sys_AW_Delivery_Methods 

    ELSE
    IF @Choice = 26	--'Business Types'
      	SELECT Slu_AC_Business_Types_ID AS [ID],  [Description] 
        FROM Slu_AC_Business_Types
        ORDER BY [Description]

    ELSE
    IF @Choice = 27 --Transaction Types - Financial ONLY
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 3 or
              Sys_AW_Transaction_Types_ID = 4 or
              Sys_AW_Transaction_Types_ID = 5 or
              Sys_AW_Transaction_Types_ID = 7 or
              Sys_AW_Transaction_Types_ID = 15 or
              Sys_AW_Transaction_Types_ID = 18 or
              Sys_AW_Transaction_Types_ID = 21 or
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 28	--'Security Types'
      	SELECT Slu_AC_Security_Types_ID as [ID] , [Description]
        FROM Slu_AC_Security_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 29	--'Information_Report Types'
      	SELECT Slu_AW_Info_Report_Types_ID as [ID] , [Description]
        FROM Slu_AW_Info_Report_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 30	--'Bond Types'
      	SELECT Slu_AC_Bond_Types_ID as [ID] , [Description]
        FROM Slu_AC_Bond_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 31	--'Customer Rating'
      	SELECT Slu_AC_Ratings_ID as [ID] , [Description]
        FROM Slu_AC_Ratings 
        ORDER BY [Description] DESC

    ELSE
    IF @Choice = 32	--'KI Scores'
      	SELECT Slu_AC_KI_Scores_ID as [ID] , [Description]
        FROM Slu_AC_KI_Scores 
        ORDER BY [Description]

    ELSE
    IF @Choice = 33	--'ITC Scores'
      	SELECT Slu_AC_ITC_Scores_ID as [ID] , [Description]
        FROM Slu_AC_ITC_Scores 
        ORDER BY [Description]

    ELSE
    IF @Choice = 34	--'Adverse Reasons'
      	SELECT Slu_AC_Adverse_Reasons_ID as [ID] , [Description]
        FROM Slu_AC_Adverse_Reasons 
        ORDER BY [Description]

    ELSE
    IF @Choice = 35	--'Nature Of Action'
      	SELECT Slu_AW_Nature_Of_Action_ID as [ID] , [Description]
        FROM Slu_AW_Nature_Of_Action 
        ORDER BY [Description]

    ELSE
    IF @Choice = 36	--'Lawsuit Type'
      	SELECT Slu_AW_Lawsuit_Types_ID as [ID] , [Description]
        FROM Slu_AW_Lawsuit_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 37	--'Court'
      	SELECT Slu_AW_Courts_ID as [ID] , [Description]
        FROM Slu_AW_Courts 
        ORDER BY [Description]

    ELSE
    IF @Choice = 38	--'Principal Type'
      	SELECT Slu_AC_Principal_Types_ID as [ID] , [Description]
        FROM Slu_AC_Principal_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 39	--'Shareholder Type'
      	SELECT Slu_AC_Shareholding_Types_ID as [ID] , [Description]
        FROM Slu_AC_Shareholding_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 40	--'Profession Type'
      	SELECT Slu_AC_Profession_Types_ID as [ID] , [Description]
        FROM Slu_AC_Profession_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 41	--'Auditor Ranking'
      	SELECT Slu_AC_Auditor_Rankings_ID as [ID] , [Description]
        FROM Slu_AC_Auditor_Rankings 
        ORDER BY [Description]

    ELSE
    IF @Choice = 42	--'Association Type'
      	SELECT Slu_AC_Association_Types_ID as [ID] , [Description]
        FROM Slu_AC_Association_Types 
        ORDER BY [Description]

    ELSE
    IF @Choice = 43	--'Bank'
      	SELECT Slu_AW_Banks_ID as [ID] , [Description]
        FROM Slu_AW_Banks 
        ORDER BY [Description]

    ELSE
    IF @Choice = 44	--'SICC Codes'
		--RL V6.0 2014-10-22 Table does not exist
		--SELECT AW_SICC_Codes_ID as [ID] , [Description]
       -- FROM AW_SICC_Codes 
       -- ORDER BY [Description]

      	SELECT 1 as [ID] , '' As [Description]

    ELSE
    IF @Choice = 45	--'Users'
      	SELECT AW_Users_ID as [ID],
               Surname + ISNULL(', ' + FirstName, '') AS [User]
        FROM AW_Users 
        ORDER BY [User]

    ELSE
    IF @Choice = 46	--'Severity Level'
      	SELECT Sys_AC_Severity_Levels_ID as [ID] , [Description]
        FROM Sys_AC_Severity_Levels 

    ELSE
    IF @Choice = 47	--'Bank Codes'
      	SELECT Slu_AC_Bank_Codes_ID as [ID] , [Description]
        FROM Slu_AC_Bank_Codes 

    ELSE
    IF @Choice = 48	--'Bank Code Terms'
      	SELECT Slu_AW_Credit_Terms_ID AS [ID],  [Description] 	
        FROM Slu_AW_Credit_Terms

    ELSE
    IF @Choice = 49	--'Customer Groups **'
      	SELECT Lup_AC_Customer_Groups_ID as [ID] , Description
        FROM Lup_AC_Customer_Groups 
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 50 --Payment Types
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 7 OR
              Sys_AW_Transaction_Types_ID = 21 OR
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 51 --Customer E-Mail addresses
        SELECT Orders_URL as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Orders_URL,'') <> ''

        UNION

        SELECT Home_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Home_Email,'') <> ''

        UNION

        SELECT Work_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Work_Email,'') <> ''

    ELSE
    IF @Choice = 52	--'Cost+Plus Category'
      	SELECT Lup_AC_Markup_Categories_ID AS [ID], [Description] 
        FROM Lup_AC_Markup_Categories
        WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]

    ELSE
    IF @Choice = 53 --'Statement Messages - Active only
        SELECT Slu_AC_Statement_Messages_ID AS [ID],
              ISNULL(Description, '') AS [Description],
              ISNULL(Message, '') AS [Message]
        FROM Slu_AC_Statement_Messages
        WHERE Slu_AW_Active_ID = 1
        ORDER BY [Description]

    ELSE
    IF @Choice = 54 --Transaction Types - Periodic Billing
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 3 or
              Sys_AW_Transaction_Types_ID = 4 or
              Sys_AW_Transaction_Types_ID = 5 or
              Sys_AW_Transaction_Types_ID = 21 or
        	  Sys_AW_Transaction_Types_ID = 22

    ELSE
    IF @Choice = 55 --Email Document Layout
        SELECT Slu_AC_Documents_ID as [ID],
			   Document_Layout AS [Description] 
        FROM Slu_AC_Documents
        ORDER BY Slu_AC_Documents_ID

    ELSE
    IF @Choice = 56 --Customer COnsignment Stock Transactions Types
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 33 or
              Sys_AW_Transaction_Types_ID = 34 or
              Sys_AW_Transaction_Types_ID = 35
    ELSE
    IF @Choice = 57 --Customer COnsignment Stock Transactions Types
        SELECT Lup_AP_Product_Bins_ID as [ID],
              [Description] AS [ProductBin]
        FROM Lup_AP_Product_Bins
        ORDER BY [Description]
    ELSE
    IF @Choice = 58 --Customer E-Mail addresses including AS_Transactions_Address_Detail
    BEGIN
        SELECT Orders_URL as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Orders_URL,'') <> ''

        UNION

        SELECT Home_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Home_Email,'') <> ''

        UNION

        SELECT Work_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Work_Email,'') <> ''

		UNION
		
        SELECT Distinct Email as [E-Mail]
        FROM AS_Transactions_Address_Detail
        WHERE AC_Customers_ID = @CompanyID
        AND ISNULL(Email,'') <> ''
	END	
END  
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Customers_InvDel]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_InvDel
--Purpose       :POS Customer Invoice and Delivery Address Details
--Date          :2013/08/08
--Authors       :RL
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
--V6.4	RL	2018-03-27	:Added Cellphone and email
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
	(    
    	 @AC_Customer_ID int
	)
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
			@WhichAddress tinyint,
			@WhichName tinyint
	
	SET @WhichAddress = 0
	SET @WhichName = 0

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SELECT @WhichAddress = ISNULL(Control_Index, 0)
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
		Control_Name = 'optPOSPrintAddress' AND
		Control_Value = 'True'

	--> Get Which Name Format To Use
	SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM Sys_AW_Options
	WHERE Control_Index = 0 AND
	Control_Type = 'CheckBox' AND
	Control_Name = 'chkPOSPrintTradeName'

    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB

	IF @WhichName = 1
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(a.Surname)) + ISNULL('', '' + A.Initials, '''') + '' / '' + IsNull(A.Firstnames,'''') AS [CurrentInvName], '
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	ELSE '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
		END	
	ELSE
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(A.Surname)) + ISNULL('', '' + A.Initials, '''') AS [CurrentInvName], '	
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
	END
	
	IF @WhichAddress = 0
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [CurrentInvPostCode], '
		END	
	ELSE
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [CurrentInvPostCode], '	
		END
		
    SET @sql = @sql + ' ISNULL(c.Tax_Number, '''') AS [TaxNumber], '
	--V6.4 Added Cell no and email
	SET @sql = @sql + '		ISNULL(c.Cell_No,'''') AS [Cell_No], '
	SET @sql = @sql + '		ISNULL(c.Orders_URL,'''') AS [Email], '	
    
	SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [CurrentDeliverAddress], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [CurrentDeliverSuburb], '
	SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [CurrentDeliverCity], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [CurrentDeliverPostCode] '

    SET @sql = @sql + ' FROM AC_Customers c '    
    SET @sql = @sql + ' WHERE c.AC_Customers_ID = ' + CONVERT(varchar(10), @AC_Customer_ID) + ' '
    
EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Tax_Rate]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Tax_Rate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Product_Tax_Rate
--Purpose       :Gets Product Tax Rate
--Date          :2018-03-28
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AP_Product_Tax_Rate]
    (    	    	
    	@Products_ID	int,
    	@Tax_Rate		Decimal(5,2) Output
    )
AS 

	SELECT @Tax_Rate = tc.Tax_Rate
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
			ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
	WHERE AP_Products_ID = @Products_ID
	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Payments_IPay_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Payments_IPay_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Payments_IPay_Select
--Purpose       :Gets IPay Details
--Date          :2018-03-28
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transaction_Payments_IPay_Select]
    (    	    	
    	@AS_Transactions_ID	int
    )
AS 

	IF @AS_Transactions_ID = 0
	BEGIN
		SELECT 
			AS_Transaction_Payments_IPay_ID, Ipay_Action, 
			AS_Transactions_ID, 
			AS_Transaction_Payments_ID, 
			IPay_ID, 
			IPay_Tran_Ref, 
			IPay_Bank_Ref, 
			IPay_URL, 
			IPay_Status,
			Amount, 
			Cell_No, 
			Email, 
			Status_Code, 
			Status_Description, 
			HTTPStatus, 
			Date_Captured
		FROM AS_Transaction_Payments_IPay
		WHERE IPay_Status = 0 
		AND IPay_Action = 'PAY SUC'
	END		
	ELSE
	BEGIN
		SELECT 
			AS_Transaction_Payments_IPay_ID, Ipay_Action, 
			AS_Transactions_ID, 
			AS_Transaction_Payments_ID, 
			IPay_ID, 
			IPay_Tran_Ref, 
			IPay_Bank_Ref, 
			IPay_URL, 
			IPay_Status,
			Amount,  
			Cell_No, 
			Email, 
			Status_Code, 
			Status_Description, 
			HTTPStatus, 
			Date_Captured
		FROM AS_Transaction_Payments_IPay
		WHERE AS_Transactions_ID = @AS_Transactions_ID
		AND IPay_Action = 'PAY SUC'
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Email_Marketing_Customers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Email_Marketing_Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Email_Marketing_Customers
--Purpose       :Retrieves Search Filter Customers
--              :ONLY FOR TRANSACTION TYPES 3 & 4 (Invoice & Refund)
--Date          :2004/07/05
--Authors       :TB
--MODS          :
--2004.2.7      :19/03/06 - Added option 14 - Account Status
--              :29/03/06 - Added option 15 - Customer with sales between dates
--V6.4	RL	2018-03-27	:Link to AS_Transactions_Address_Detail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Email_Marketing_Customers]
    (
        @CompanyID int, 
        @Option int,
        @FetchChoice int,
        @Value int,
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON

-- Exec sp_AS_Select_Email_Marketing_Customers 1, 16, 1, 500, '2017-01-01', '2018-03-31'

-- Clear table 
TRUNCATE TABLE [AS_Email_Marketing];

-->ALL Customers
    IF @Option = 0
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
               c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END
    ELSE
-->All Customers with Sales
    IF @Option = 1
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
												Transaction_Date <= @EndDate AND
												(Sys_AW_Transaction_Types_ID = 3 OR
												 Sys_AW_Transaction_Types_ID = 4)
									)                                    

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->All Customers with No Sales
    IF @Option = 2
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])    
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID NOT IN
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       (Sys_AW_Transaction_Types_ID = 3 OR
                        Sys_AW_Transaction_Types_ID = 4)) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID NOT IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
												Transaction_Date <= @EndDate AND
												(Sys_AW_Transaction_Types_ID = 3 OR
												 Sys_AW_Transaction_Types_ID = 4)
									)                                                  

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END        
    ELSE
-->TOP 20%
    IF @Option = 3
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	Distinct
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
									)                              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->NEXT 30%
    IF @Option = 4
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
											LEFT JOIN dbo.fn_AS_Top20Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
												ON a.CustomerID = b.CustomerID
										WHERE b.CustomerID IS NULL
									)                              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->LAST 50%
    IF @Option = 5
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT  a.[CustomerID],
                a.[Send E-Mail],
                a.[Customer],
                a.[Number],
                a.[Contact E-mail],
                a.[Contact Cell],
                a.[Post Box],
                a.[Post Office],
                a.[Post Code]
        FROM dbo.fn_AS_Top100Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
            LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
                ON a.CustomerID = b.CustomerID
        WHERE b.CustomerID IS NULL

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT a.[CustomerID]
										FROM dbo.fn_AS_Top100Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) a
											LEFT JOIN dbo.fn_AS_Top50Perc_Customers_GP_Extended(@CompanyID, @FetchChoice, @StartDate, @EndDate) b
												ON a.CustomerID = b.CustomerID
										WHERE b.CustomerID IS NULL
									)                      

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Salesperson
    IF @Option = 6
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AS_Reps_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AS_Reps_ID = @Value
									)              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Sales Area
    IF @Option = 7
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Sales_Areas_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Sales_Areas_ID = @Value 
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Language
    IF @Option = 8
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Languages_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Slu_AW_Languages_ID = @Value 
									)                                                                                    

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Type
    IF @Option = 9
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Customer_Types_ID = @Value 
									)                                                                      

		SELECT	DISTINCT	
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Credit Terms
    IF @Option = 10
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Slu_AW_Credit_Terms_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Slu_AW_Credit_Terms_ID = @Value 
									)                                                        

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Discount Category
    IF @Option = 11
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])        
        SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Discount_Categories_ID = @Value
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Discount_Categories_ID = @Value
									)                                          

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Group
    IF @Option = 12
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Lup_AC_Customer_Groups_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Lup_AC_Customer_Groups_ID = @Value 
									)                            

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Account Type
    IF @Option = 13
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Types_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Sys_AC_Account_Types_ID = @Value
									)              

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Account Status
    IF @Option = 14
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Sys_AC_Account_Status_ID = @Value 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Sys_AC_Account_Status_ID = @Value 
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->New Customers (Start Date)
    IF @Option = 15
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.Start_Date >= @StartDate AND
              c.Start_Date <= @EndDate AND
              c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AC_Customers
										WHERE Start_Date >= @StartDate AND
												Start_Date <= @EndDate
									)

		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
    END
    ELSE
-->Customer Sales
    IF @Option = 16
    BEGIN
		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])                
		SELECT c.AC_Customers_ID AS [CustomerID], 
               c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
               LEFT(CASE WHEN c.Firstnames IS NULL and c.Initials IS NULL
                         THEN ISNULL(Surname, '')
                         ELSE ISNULL(Surname, '') + ', ' + 
                              LTRIM(ISNULL(Firstnames, '') + ' ' + 
                                    ISNULL(t.Description, '') + ' ' +
                                    ISNULL(Initials, ''))
                    END, 50) AS [Customer],
    		   c.Customer_Number AS [Number],
               c.Home_Email AS [Contact E-mail],
               c.Cell_No AS [Contact Cell], 
               c.Post_Box AS [Post Box],
               c.Post_Office AS [Post Office],
               c.Post_Code AS [Post Code]
        FROM AC_Customers c
            LEFT JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        WHERE c.AC_Customers_ID in
                (SELECT distinct AC_Customers_ID
                 FROM AS_Transactions
                 WHERE Transaction_Date >= @StartDate AND
                       Transaction_Date <= @EndDate AND
                       Sys_AW_Transaction_Types_ID = 3) 
              AND c.AW_User_Companies_ID = @CompanyID

		INSERT INTO [AS_Email_Marketing] ([AC_Customers_ID], [Send_Email], [Customer], [Customer_Number], [Home_Email],
        									[Cell_No],[Post_Box],[Post_Office],[Post_Code])
		SELECT	DISTINCT
				t.AC_Customers_ID AS [CustomerID], 
				c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
				t.Customer_Name AS [Customer],
				c.Customer_Number AS [Number],
				t.Email AS [Contact E-mail],
				t.Cell_No AS [Contact Cell], 
				c.Post_Box AS [Post Box],
				c.Post_Office AS [Post Office],
				c.Post_Code AS [Post Code]
		FROM AC_Customers c
			INNER JOIN AS_Transactions_Address_Detail t
				ON c.AC_Customers_ID = t.AC_Customers_ID
		WHERE (t.Email <> '' Or t.Cell_No <> '')	
		AND c.AC_Customers_ID IN	(
										SELECT DISTINCT AC_Customers_ID
										FROM AS_Transactions
										WHERE Transaction_Date >= @StartDate AND
											  Transaction_Date <= @EndDate AND
											  Sys_AW_Transaction_Types_ID = 3
									)
    
		SELECT	DISTINCT
				[AC_Customers_ID] As [CustomerID], 
				[Send_Email] As [Send E-Mail], 
				[Customer] AS [Customer],
				[Customer_Number] AS [Number],
				[Home_Email] AS [Contact E-mail],
				[Cell_No] AS [Contact Cell], 
				[Post_Box] AS [Post Box],
				[Post_Office] AS [Post Office],
				[Post_Code] AS [Post Code]
        FROM [AS_Email_Marketing]
        ORDER BY [Customer]
	END
SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Payment_Unallocate]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Payment_Unallocate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Payment_Unallocate
--Purpose       :CURSOR - Reverses Supplier Payment Allocations for a specific Payment
--Functionality :UPDATE AO_Transactions - Reset the SOURCE (Invoice, ORIGINAL) transaction to its pre-payment ALLOCATION state
--				:UPDATE AO_Transactions - Reset the DESTINATION (Payment, ORIGINAL) transaction to its pre-payment ALLOCATION state
--              :UPDATE AO_Suppliers    - Add back the payment to the Suppliers Account Balance
--              :DELETE AO_Transactions_Transactions
--Date          :2016-03-14
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Payment_Unallocate]
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @Linked_AO_Transactions_ID			Int,
			@Payment_Amount						Decimal(18,2),
			@Allocated_Amount					Decimal(18,2),
			@Amount								Decimal(18,2),
			@ReturnCode							Int,
			@AO_Transactions_Transactions_ID	Int,
			@AllocationFound					Int,
			@NEW_PaymentTranID					Int,
			@Transactions_Type_ID				Int,
			@Rev_JRN							Int,
			@Temp_PaymentTranID					Int

	DECLARE @Temp_Table TABLE
	(
		AO_Transactions_Transactions_ID	Int,
		Source_ID						Int,
		Destination_ID					Int,
		Amount							Decimal(18,2)
	)
	
	SELECT @ReturnCode = 0
	SELECT @AllocationFound = 0
	SELECT @Rev_JRN = 0

	--Check if allocated amount is same as payment amount
	SELECT	@Payment_Amount = Payment_Amount,
			@Transactions_Type_ID = Sys_AW_Transaction_Types_ID
	FROM AO_Transactions
	WHERE AO_Transactions_ID = @PaymentTranID


		IF @Payment_Amount < 0
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			)
			BEGIN	
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Source_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Destination_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @Temp_PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
			ELSE			
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Destination_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Source_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @Temp_PaymentTranID
			END
			ELSE			
			BEGIN
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Destination_AO_Transactions_ID, Source_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Source_AO_Transactions_ID, Destination_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
		END
		ELSE
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Source_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Source_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
				AND t.Total_Amount = 0				
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Destination_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @Temp_PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
			ELSE			
			IF EXISTS
			(
				SELECT 1
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0
			)
			BEGIN
				SELECT @Rev_JRN = 1
				SELECT @Temp_PaymentTranID = 0
				
				SELECT @Temp_PaymentTranID = ISNULL(Destination_AO_Transactions_ID,0)
				FROM AO_Transactions_Transactions tt
					INNER JOIN AO_Transactions t
						ON t.AO_Transactions_ID = tt.Destination_AO_Transactions_ID
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
				AND t.Total_Amount = 0		
				
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, 0, Source_AO_Transactions_ID, Amount
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @Temp_PaymentTranID
			END
			ELSE			
			BEGIN
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Destination_AO_Transactions_ID, Source_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
			
				INSERT INTO @Temp_Table (AO_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
				SELECT AO_Transactions_Transactions_ID, Source_AO_Transactions_ID, Destination_AO_Transactions_ID, (Amount)
				FROM AO_Transactions_Transactions
				WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AO_Transactions_ID,0) <> 0
			END
		END		
		IF EXISTS
		(
			SELECT 1
			FROM @Temp_Table
			WHERE Source_ID = 0
		)
		BEGIN
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM @Temp_Table
			WHERE Destination_ID <> @PaymentTranID
			
			SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM @Temp_Table
		
			SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2		
		END

	IF @ReturnCode = 0
	BEGIN
			DECLARE GetData CURSOR
			FOR
			SELECT AO_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 

		OPEN GetData

		FETCH NEXT FROM GetData INTO @AO_Transactions_Transactions_ID, @Linked_AO_Transactions_ID, @Amount
		WHILE @@Fetch_Status = 0
		BEGIN
			SELECT @AllocationFound = 1
			SELECT @ReturnCode = 1
			
				IF @Rev_JRN = 1
				BEGIN
					UPDATE AO_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AO_Transactions_ID = @Linked_AO_Transactions_ID			
				END
				ELSE
				BEGIN
					IF @Payment_Amount <> 0
					BEGIN
						UPDATE AO_Transactions
						SET Payment_Amount = Payment_Amount - @Payment_Amount
						WHERE AO_Transactions_ID = @PaymentTranID
						
						SELECT @Payment_Amount = 0
					END

					UPDATE AO_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AO_Transactions_ID = @Linked_AO_Transactions_ID				
				END
			
			DELETE AO_Transactions_Transactions			
			WHERE AO_Transactions_Transactions_ID = @AO_Transactions_Transactions_ID	
		
			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AO_Transactions_ID,0) = 0
				
			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = @Linked_AO_Transactions_ID
			AND ISNULL(Destination_AO_Transactions_ID,0) = 0

			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = 0
			AND ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID

			DELETE AO_Transactions_Transactions			
			WHERE ISNULL(Source_AO_Transactions_ID,0) = 0
			AND ISNULL(Destination_AO_Transactions_ID,0) = @Linked_AO_Transactions_ID		
		
		FETCH NEXT FROM GetData INTO @AO_Transactions_Transactions_ID, @Linked_AO_Transactions_ID, @Amount
		END
		CLOSE GetData
		DEALLOCATE GetData
	END

	IF @ReturnCode = 1
	BEGIN
		DELETE AO_Transactions_Transactions
		WHERE ISNULL(Destination_AO_Transactions_ID,0) = @PaymentTranID
	END

--1 Success
--0 Error
--2 Allocation Amount not same as payment Amount
SET NOCOUNT OFF
RETURN @ReturnCode
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Payment_Unallocate]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Payment_Unallocate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Payment_Unallocate
--Purpose       :CURSOR - Reverses Customer Payment Allocations for a specific Payment
--Date          :2018-03-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Payment_Unallocate]
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )
AS

SET NOCOUNT ON

	--Transaction handled in code
    -----------------------------------------------------------
    --BEGIN TRAN Reverse_Payment
    -----------------------------------------------------------

	DECLARE @Linked_AS_Transactions_ID			Int,
			@Payment_Amount						Decimal(18,2),
			@Allocated_Amount					Decimal(18,2),
			@Amount								Decimal(18,2),
			@ReturnCode							Int,
			@AS_Transactions_Transactions_ID	Int,
			@Transactions_Type_ID				Int,
			@Rev_JRN							Int

	DECLARE @Temp_Table TABLE
	(
		AS_Transactions_Transactions_ID	Int,
		Source_ID						Int,
		Destination_ID					Int,
		Amount							Decimal(18,2)
	)
	

	SELECT @ReturnCode = 0
	SELECT @Rev_JRN = 0

	--Check if allocated amount is same as payment amount
	SELECT	@Payment_Amount = Payment_Amount,
			@Transactions_Type_ID = Sys_AW_Transaction_Types_ID
	FROM AS_Transactions
	WHERE AS_Transactions_ID = @PaymentTranID

	IF @Transactions_Type_ID = 4
	BEGIN
--Select 1

		IF @Payment_Amount < 0
		BEGIN
--Select 2
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE
		BEGIN
--Select 3
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END		
--Select 4				
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM @Temp_Table
	
		SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE 
	IF @Transactions_Type_ID = 5
	BEGIN
--Select 5	
		IF @Payment_Amount < 0
		BEGIN
--Select 6
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE
		BEGIN
--Select 7
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END		
--Select 8
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM @Temp_Table
	
		SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE 
	IF @Transactions_Type_ID = 7
	BEGIN
--Select 9

		IF @Payment_Amount < 0
		BEGIN
--Select 10
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE
		BEGIN
--Select 11
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END		
--Select 12				
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM @Temp_Table
	
		SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE 
	IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
	BEGIN
--Select 13
		IF @Payment_Amount < 0
		BEGIN
--Select 14		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount)
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE
		BEGIN
--Select 15		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Source_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
			INSERT INTO @Temp_Table (AS_Transactions_Transactions_ID, Source_ID, Destination_ID, Amount)	
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Destination_AS_Transactions_ID, ABS(Amount) * -1
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END		
--Select 16				
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM @Temp_Table
		
		SELECT @Allocated_Amount = ISNULL(@Allocated_Amount,0)
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE
	BEGIN
--Select 17
		--Scenario not tested
		SELECT @ReturnCode = 2
	END
--Select @ReturnCode As '@ReturnCode'
	IF @ReturnCode = 0
	BEGIN
--Select 18
		IF @Transactions_Type_ID = 4
		BEGIN
--Select 19
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 
		END
		ELSE 
		IF @Transactions_Type_ID = 5
		BEGIN
--Select 20
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 
		END
		ELSE 
		IF @Transactions_Type_ID = 7
		BEGIN
--Select 21
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 
		END
		ELSE 
		IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
		BEGIN
--Select 22		
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_ID, Amount
			FROM @Temp_Table 
		END
		
		OPEN GetData

		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		WHILE @@Fetch_Status = 0
		BEGIN
--Select 23
			SELECT @ReturnCode = 1
			
			IF @Transactions_Type_ID = 4
			BEGIN
--Select 24
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE 
			IF @Transactions_Type_ID = 5
			BEGIN
--Select 25
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE 
			IF @Transactions_Type_ID = 7
			BEGIN
--Select 26
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE 
			IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
			BEGIN
--Select 27
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE
			BEGIN
--Select 28
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
--Select 29
			DELETE AS_Transactions_Transactions			
			WHERE AS_Transactions_Transactions_ID = @AS_Transactions_Transactions_ID	

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0
				
			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID

--Select 30
		
		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		END
		CLOSE GetData
		DEALLOCATE GetData
	END
--Select 31
	--When an allocation is done via the Unallocated Payments screen it adds a record to 
	--AS_Transactions_Transactions with a NULL Source_AS_Transactions_ID. Fuck knows why !!!
	
	--Exec sp_AS_Payment_Unallocate_2 @PaymentTranID, @UserID, @CompanyID
        
        
	IF @ReturnCode = 1
	BEGIN
		DELETE AS_Transactions_Transactions
		WHERE ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
		DELETE AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID		
	END

--Transaction handled in code		
--IF @ReturnCode = 1
--	COMMIT TRAN Reverse_Payment
--ELSE
--	ROLLBACK TRAN Reverse_Payment

--1 Success
--0 Error
--2 Allocation Amount not same as payment Amount
SET NOCOUNT OFF
RETURN @ReturnCode
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Number_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Number_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :The POS SELECT Transaction Number For E-Mail
--Date          :2018-04-09
--Authors       :RL
--Version       :6.4
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Number_Select]
    (
        @DocumentID int,
        @Transaction_Number	varchar(19) OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @Transaction_Number = Transaction_Number
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID

	IF @Transaction_Number IS NULL 
        BEGIN	
    		SET @Transaction_Number = ''
        END
		
SET NOCOUNT OFF
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Top100Perc_Products_GP]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Top100Perc_Products_GP]
GO
--Description   : fn_AP_Top100Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 100% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Top100Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Top20Perc_Products_GP]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Top20Perc_Products_GP]
GO
--Description   : fn_AP_Top20Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 20% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------
CREATE           FUNCTION [dbo].[fn_AP_Top20Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Top50Perc_Products_GP]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Top50Perc_Products_GP]
GO
--Description   : fn_AP_Top50Perc_Products_GP
--Purpose       : FUNCTION TO EXTRACT Top 50% Products
--              : By Gross Profit
--Parameters    :
--Date          : 22 SEP 2001
--Authors       : TB
--Version       : 1.0.0
-------------------------------------------------------------------------------

CREATE           FUNCTION [dbo].[fn_AP_Top50Perc_Products_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @Product_GP_Table TABLE 
	(
        [ID] int,
        [Product] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Code] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartPeriodNo int, @EndPeriodNo int
     IF @DataChoice = 0
        BEGIN
            SET @StartPeriodNo = CONVERT(int, @StartDate) / 7
            SET @EndPeriodNo = CONVERT(int, @EndDate) / 7

        	INSERT @Product_GP_Table
        
            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Transaction_Date > @StartDate AND
                  h.Transaction_Date <= @EndDate) AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR
                  h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartPeriodNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndPeriodNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @Product_GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                p.AP_Products_ID as [ID],
                MAX(p.Description) as [Product],
                MAX(p.Product_Code) as [Code]
            FROM AS_Transaction_Details d
                    INNER JOIN AS_Transactions h ON d.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AP_Products p ON d.AP_Products_ID = p.AP_Products_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartPeriodNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndPeriodNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY p.AP_Products_ID
            ORDER BY SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) DESC
        END
    RETURN 
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AS_Top100Perc_Customers_GP]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP]
GO
-------------------------------------------------------------------------------
--Description   : fn_AS_Top100Perc_Customers_GP
--Purpose       : FUNCTION TO EXTRACT Top 100% Customers
--              : By Gross Profit WITHIN THE LAST 1 YEAR
--Parameters    :
--Date          : 08 JUL 2001
--Authors       : TB
--Version       : 1.0.0
--MODS          :13/05/02 - Fixed overflow error with: LEFT([Customer Name],50) 
--              :05/07/04 - Renamed [Customer Number] field to [Number]
-------------------------------------------------------------------------------

CREATE             FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP]
    (
        @CompanyID int, 
        @DataChoice int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [ID] int,
        [Customer Name] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @DataChoice = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table
        
            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID as [ID],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer Name],
                MAX(c.Customer_Number) as [Number]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AS_Top100Perc_Customers_GP_Extended]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP_Extended]
GO
-------------------------------------------------------------------------------
--Description   :fn_AS_Top100Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 100% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top100Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 100 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AS_Top20Perc_Customers_GP_Extended]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AS_Top20Perc_Customers_GP_Extended]
GO
-------------------------------------------------------------------------------
--Description   :fn_AS_Top20Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 20% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top20Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN

  	DECLARE @StartWeekNo int, @EndWeekNo int


    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 20 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AS_Top50Perc_Customers_GP_Extended]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AS_Top50Perc_Customers_GP_Extended]
GO
-------------------------------------------------------------------------------
--Description   :fn_AS_Top50Perc_Customers_GP_Extended
--Purpose       :EXTRACT Top 50% Customers by GP%
--              :By Gross Profit for selected Period
--Returns       :TABLE
--Date          :2004/07/07
--Authors       :TB
--MODS          :16/03/06 - Added extract LEFT of varchars to eliminate TRUNCATE
-------------------------------------------------------------------------------

CREATE               FUNCTION [dbo].[fn_AS_Top50Perc_Customers_GP_Extended]
    (
        @CompanyID int, 
        @Period int,
        @StartDate datetime,
        @EndDate datetime
    )

RETURNS @GP_Table TABLE 
	(
        [CustomerID] int,
        [Send E-mail] tinyint,
        [Customer] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Number] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact E-mail] varchar(40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Contact Cell] varchar(16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Box] varchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Office] varchar(30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [Post Code] varchar(10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    )

AS

BEGIN
  	DECLARE @StartWeekNo int, @EndWeekNo int
    IF @Period = 0
        BEGIN
            SET @StartWeekNo = CONVERT(int, @StartDate) / 7
            SET @EndWeekNo = CONVERT(int, @EndDate) / 7
        
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (CONVERT(int, h.Transaction_Date) / 7 > @StartWeekNo AND
                   CONVERT(int, h.Transaction_Date) / 7 <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
-----------------------------------------------------------------------------------
    ELSE
        BEGIN
            SET @StartWeekNo = dbo.fn_AS_Get_Month_Number(@StartDate)
            SET @EndWeekNo = dbo.fn_AS_Get_Month_Number(@EndDate)
    
        	INSERT @GP_Table

            SELECT TOP 50 PERCENT WITH TIES
                c.AC_Customers_ID AS [CustomerID], 
                MAX(c.AW_YesNo_Send_Email_ID) AS [Send E-Mail],
                LEFT(MAX(CASE WHEN Firstnames IS NULL and Initials IS NULL
                    THEN ISNULL(Surname,'')
                    ELSE ISNULL(Surname,'') + ', ' + 
                         LTRIM(ISNULL(Firstnames,'') + ' ' + 
                               ISNULL(t.Description,'') + ' ' +
                               ISNULL(Initials,''))
                    END),50) as [Customer],
        		LEFT(MAX(c.Customer_Number), 10) AS [Number],
                LEFT(MAX(c.Home_Email), 40) AS [Contact E-mail],
                LEFT(MAX(c.Cell_No), 16) AS [Contact Cell], 
                LEFT(MAX(c.Post_Box), 20) AS [Post Box],
                LEFT(MAX(c.Post_Office), 30) AS [Post Office],
                LEFT(MAX(c.Post_Code), 10) AS [Post Code]
            FROM AC_Customers c
                    INNER JOIN AS_Transactions h ON c.AC_Customers_ID = h.AC_Customers_ID
                    INNER JOIN Slu_AW_Titles t ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
            WHERE h.AW_User_Companies_ID = @CompanyID AND
                  (dbo.fn_AS_Get_Month_Number(h.Transaction_Date) > @StartWeekNo AND
                   dbo.fn_AS_Get_Month_Number(h.Transaction_Date) <= @EndWeekNo) AND
                  (h.Sys_AW_Transaction_Types_ID = 3 OR
                   h.Sys_AW_Transaction_Types_ID = 4)
            GROUP BY c.AC_Customers_ID
            ORDER BY SUM((h.Total_Amount - h.Total_Tax_Amount) - h.Total_Cost) DESC
        END
    RETURN
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Lookups_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Lookups_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Lookups_Select
--Purpose       :POS Look-ups
--Date          :2002/02/06
--Authors       :TB
--Version       :1.0.0
--MODS          :09/07/03 - Added select ONLY ACTIVE Sys_AW_Payment_Methods from
--              :           NEW Slu_AW_Active_ID column in Sys_AW_Payment_Methods
--              :           (modified esspecially for !! Autowiel !!)
--              :31/01/04 - Added new 'CBilling' Lookup from Slu_AS_Card_Institutions
--              :29/02/04 - Added new Central Billing 'Fail Reasons' Lookup
--              :02/04/04 - Added new Central Billing 'Billing Providers' Lookup
--              :03/04/04 - Removed 'CBilling' Lookup from Slu_AS_Card_Institutions
--              :09/04/04 - Added new Central Billing 'Claim Codes' Lookup
--              :20/08/04 - Added new Lup_AC_Customer_Groups Lookup for Add/Edit
--2004.3.7      :24/07/07 - Added new Customer Cost+Plus as 'CostPlus'
--              :01/09/07 - Added ACTIVE validation in 'Discounts' for Customer Discounts
--2004.3.8      :29/05/08 - Added ORDER BY for Reps
--2004.4.8      :11/05/10 - Added fetch only Active Reps
--V6.4	RL	2018-04-11	:Option Methods. Removed i-Pay from drop down list
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Lookups_Select]
    (
       @DataMember varchar(20),
       @CompanyID int,
       @Filter int = 0
    )

AS

SET NOCOUNT ON

    IF @DataMember = 'Account Statuses'
        SELECT Sys_AC_Account_Status_ID as [ID],
               [Description]
        FROM Sys_AC_Account_Status
    
    ELSE
    IF @Datamember = 'Banks'
        SELECT Slu_AW_Banks_ID as [ID],
               [Description]
        FROM Slu_AW_Banks
    
    ELSE
    IF @DataMember = 'Customer Type'
        SELECT Lup_AC_Customer_Types_ID as [ID],
               [Description]
        FROM Lup_AC_Customer_Types
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'Methods'
        SELECT Sys_AW_Payment_Methods_ID as [ID],
               [Description],
               Sys_AW_Institution_Types_ID as [InstitutionType]
        FROM Sys_AW_Payment_Methods
        WHERE Slu_AW_Active_ID = 1 AND
              NOT (Sys_AW_Payment_Methods_ID = 1 OR
                   Sys_AW_Payment_Methods_ID = 2 OR
                   Sys_AW_Payment_Methods_ID = 7 OR
                   Sys_AW_Payment_Methods_ID = 10 OR
                   Sys_AW_Payment_Methods_ID = 14)
    
    ELSE
    IF @DataMember = 'Institutions'
        SELECT Slu_AS_Card_Institutions_ID as [ID],
               [Description]
        FROM Slu_AS_Card_Institutions
        WHERE Sys_AW_Institution_Types_ID = 3
    
    ELSE
    IF @DataMember = 'Workstations'
        SELECT Lup_AW_Workstations_ID as [ID],
               [Description]
        FROM Lup_AW_Workstations
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Tills'
        SELECT Lup_AS_Tills_ID as [ID],
               [Description]
        FROM Lup_AS_Tills
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'Reps'
        SELECT Lup_AS_Reps_ID as [ID],
               [Description]
        FROM Lup_AS_Reps
        WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Active_ID = 1
        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Asset Types'
        SELECT Lup_AC_Asset_Types_ID as [ID],
               [Description]
        FROM Lup_AC_Asset_Types
    
    ELSE
    IF @DataMember = 'Users'
        SELECT a.AW_Users_ID as [ID],
               a.UserName  
        FROM AW_Users a
            JOIN AW_Company_Users b
                ON a.AW_Users_ID = b.AW_Users_ID
        WHERE b.AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'PLU'
        SELECT Lup_AP_PLU_Tabs_ID as [ID],
               [Description],
               Tab_No as [Tab]
        FROM Lup_AP_PLU_Tabs
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Types'
        SELECT Lup_AP_Product_Types_ID as [ID],
               [Description]
        FROM Lup_AP_Product_Types 
        WHERE AW_User_Companies_ID = @CompanyID
        UNION SELECT 0, '<All>' 
        ORDER BY [Description]
    
    ELSE
    IF @DataMember = 'Switch1'
        SELECT AP_Switch1_ID as [ID],
               [Description]
        FROM AP_Switch1
        WHERE AW_User_Companies_ID = @CompanyID
    
    ELSE
    IF @DataMember = 'Filter_Switch2'
        SELECT AP_Switch2_ID as [ID],
               [Description],
               AP_Switch1_ID as [FKID]
        FROM AP_Switch2 
    
    ELSE
    IF @DataMember = 'Filter_Switch3'
        SELECT AP_Switch3_ID as [ID],
               [Description],
               AP_Switch2_ID as [FKID]
    FROM AP_Switch3
    
    ELSE
    IF @DataMember = 'Discounts'
    	SELECT AS_Discount_Categories_Groups_ID as [ID],
               Lup_AP_Discount_Groups_ID as [GroupID],
               Lup_AC_Discount_Categories_ID as [CategoryID],
               Discount_Percentage as [Perc]
    	FROM AS_Discount_Categories_Groups
        WHERE Slu_AW_Active_ID = 1

    ELSE
    IF @DataMember = 'Fail Reasons'
        SELECT Lup_AP_Fail_Reasons_ID as [ID],
               [Description]
        FROM Lup_AP_Fail_Reasons
        ORDER BY Lup_AP_Fail_Reasons_ID

    ELSE
    IF @DataMember = 'Billing Providers'
        SELECT Lup_AS_CBilling_Providers_ID as [ID],
               [Description]
        FROM Lup_AS_CBilling_Providers
        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Claim Codes'
        SELECT Lup_AP_Claim_Codes_ID as [ID],
               [Description]
        FROM Lup_AP_Claim_Codes
--        ORDER BY [Description]

    ELSE
    IF @DataMember = 'Customer Groups'
        SELECT Lup_AC_Customer_Groups_ID as [ID],
               [Description]
        FROM Lup_AC_Customer_Groups
        WHERE AW_User_Companies_ID = @CompanyID

    ELSE
    IF @DataMember = 'CostPlus'
    	SELECT AS_Markup_Categories_Groups_ID as [ID],
               Lup_AP_Markup_Groups_ID as [GroupID],
               Lup_AC_Markup_Categories_ID as [CategoryID],
               Markup_Percentage as [Perc]
    	FROM AS_Markup_Categories_Groups

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_GL_Source_View_AP]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_GL_Source_View_AP]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_22CJ
--Functionality :Fetch GL Supplier Transaction using [AB_GL_Transactions.AB_Transaction_Ref]
--              :    AB_GL_Transactions JOIN AO_Transactions
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_AP]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' d.Supplier_Name AS [Supplier] '
   
    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AO_Transactions c '
    SET @sql = @sql + '         ON c.AO_Transactions_ID = a.AB_Transaction_Ref '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers d '
    SET @sql = @sql + '         ON d.AO_Suppliers_ID = c.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
    --R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_GL_Source_View_AR]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_GL_Source_View_AR]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_22CJ
--Functionality :Fetch GL Customer Journals using [AB_GL_Transactions.AB_Transaction_Ref]
--              :    AB_GL_Transactions JOIN AS_Transactions
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_AR]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount], '
    SET @sql = @sql + ' d.Surname AS [Customer] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions c '
    SET @sql = @sql + '         ON c.AS_Transactions_ID = a.AB_Transaction_Ref '
    SET @sql = @sql + '     LEFT JOIN AC_Customers d '
    SET @sql = @sql + '         ON d.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
	--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_GL_Source_View_GL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_GL_Source_View_GL]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_GL_Source_View_GL
--Functionality :Fetch GL Year-End using [AB_GL_Transactions.AB_Transaction_Ref]
--Date          :2006/02/27
--Authors       :TB
--MODS:         :
--R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_GL_Source_View_GL]
    (
            @CompanyID int,
            @TranDate datetime,
            @Refno int,
            @TranTypeID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' a.AB_GL_Transactions_ID AS [ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountsID], '
    SET @sql = @sql + ' a.Sys_AB_Transaction_Types_ID AS [Transaction Type], '
    SET @sql = @sql + ' a.AB_Source_Ref AS [Source Ref], '
    SET @sql = @sql + ' a.AB_Transaction_Ref AS [Ref No], '
    SET @sql = @sql + ' a.[Description] AS [Narration], '

    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) AS [Date], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') + '' - '' + ISNULL(b.Account_Number, '''') + '' ('' + ' +
                      '     CONVERT(varchar(20), b.AB_Accounts_ID) + '')''  AS [Account], '

    SET @sql = @sql + ' e.[Description] AS [Month], '
    SET @sql = @sql + ' f.[Description] AS [Year], '
--     SET @sql = @sql + ' a.Slu_AW_Months_ID AS [Month], '
--     SET @sql = @sql + ' a.Slu_AW_Years_ID AS [Year], '

    SET @sql = @sql + ' a.AB_Transaction_Amount AS [Amount] '

    SET @sql = @sql + ' FROM AB_GL_Transactions a '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts b '
    SET @sql = @sql + '         ON b.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months e '
    SET @sql = @sql + '         ON e.Slu_AW_Months_ID = a.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years f '
    SET @sql = @sql + '         ON f.Slu_AW_Years_ID = a.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users g '
    SET @sql = @sql + '         ON g.AW_Users_ID = a.[User_ID] '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND LEFT(CONVERT(CHAR(10), a.AB_Transaction_Date, 121), 10) = ' + '''' + LEFT(CONVERT(CHAR(10), @TranDate, 121), 10) + '''' + ' '
    SET @sql = @sql + '   AND a.AB_Transaction_Ref = ' + CONVERT(varchar(10), @Refno) + ' '
    --R.L V6.4 Settlement Tax was moved to a different transaction type for the Tax report
    --SET @sql = @sql + '   AND a.Sys_AB_Transaction_Types_ID = ' + CONVERT(varchar(10), @TranTypeID) + ' '
    

    SET @sql = @sql + ' ORDER BY a.AB_GL_Transactions_ID '


    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Transaction_History_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Transaction_History_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------
--Description   :sp_AO_Transaction_Headers_Select
--Purpose       :SELECT Transactions History for Supplier Catalog & Invoicing
--Functionality :
--Parameters    : 
--Date          :2002/01/18
--Authors       :TB
--Version       :1.0.0
--MODS          :28/10/02 - Modified some Column Headings to reduce size
--              :28/10/02 - Added @MonthsID & @YearsID for Reports
--              :12/12/04 - Added field [TranTypeID] for Payment Reversal
--              :16/12/04 - Renamed field t.Document_Number from [Ref No] to [Doc No]
--              :16/12/04 - Added field t.Supplier_Reference AS [Ref No]
--              :16/12/04 - Changed [Date] field format to CHAR(10)
--              :17/12/04 - Changed [Date] field format back to unformatted
--              :           because it is used when selecting CASHBOOK TranID
--              :           in Supplier Payment Reversals
--              :18/12/04 - Added field t.Settlement_Discount AS [Settlement]
--2004.3.5      :20/06/07 - Moved [Comment] after [Payment] field
--2004.3.8      :30/05/08 - Moved [Captured] after [Doc No] field
--              :30/05/08 - Moved [Settlement] after [Comment] field
--              :30/05/08 - Changed ORDER BY to t.Date_Captured DESC to enable
--              :           viewing WHEN BACK DATED transactions were posted
--              :30/05/08 - Added fetch transactions FROM an Accounting Period
--              :           instead of for ONE Accounting Period
--V6.4	RL	2018-04-19	:Hide Zero transaction payments that are created by the system!!!!
--------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Transaction_History_Select]
	(
    	@SupplierID int,
        @TransactionTypeID int = 0,
    	@StartDate datetime = NULL,
    	@EndDate datetime = NULL,
    	@Company_ID int,
    	@MonthsID int = NULL, 
    	@YearsID int = NULL
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @StartPeriod varchar(6)


    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthsID, @YearsID)


    SET @sql = ' SELECT ' +
                    ' t.AO_Transactions_ID As [ID], ' +
                    ' t.AO_Suppliers_ID, ' +
                    ' tt.[Description] AS [Type], ' +
                    ' t.Supplier_Reference AS [Ref No], ' +
                    ' t.Date_Captured AS [Captured], ' +
                    ' t.Document_Number AS [Doc No], ' +
                    ' t.Document_Date AS [Date], ' +
                    ' m.[Description] AS [Month], ' +
                    ' y.[Description] AS [Year], ' +
                    ' t.Net_Amount AS [Amount], ' +
                    ' t.Total_Tax_Amount [Tax], ' +
                    ' t.Total_Amount AS [Total], ' +
                    ' t.Payment_Amount AS [Payment], ' +
                    ' t.Settlement_Discount AS [Settlement], ' +
                    ' t.Comment AS [Comment], ' +
--                    ' t.Settlement_Discount AS [Settlement], ' +
                    ' t.Trade_Discount_Total AS [Trade Disc], ' +
                    ' t.Rebate_Discount_Total AS [Rebate Disc], ' +
                    ' t.Other_Discount_Total AS [Other Disc], ' +
--                    ' t.Date_Captured AS [Captured], ' +
                    ' u.UserName AS [User], ' +
                    ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID] ' +

    			' FROM AO_Transactions t ' +
                    ' LEFT JOIN Sys_AW_Transaction_Types tt ' +
    				    ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID ' +
                    ' LEFT JOIN Slu_AW_Months m ' +
                        ' ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID ' +
                    ' LEFT JOIN Slu_AW_Years y ' +
                        ' ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID ' +
                    ' LEFT JOIN AW_Users u ' +
                        ' ON t.User_ID = u.AW_Users_ID '

--WHERE
    SET @sql = @sql +
                ' WHERE t.AO_Suppliers_ID = ' + CONVERT(VARCHAR(10), @SupplierID) + ' AND ' +
                '       t.AW_User_Companies_ID = ' + CONVERT(VARCHAR(10), @Company_ID)

--Additional WHERE
    IF @TransactionTypeID <> 0    -- Specific TRANSACTION TYPE
        BEGIN
            SET @sql = @sql + ' AND t.Sys_AW_Transaction_Types_ID = ' + CONVERT(VARCHAR(10), @TransactionTypeID)
        END

    IF NOT @StartDate IS NULL OR NOT @EndDate IS NULL    --Between Dates
        BEGIN
            SET @sql = @sql + ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @StartDate) + ''') <= 0 ' +
                              ' AND DATEDIFF(d, t.Document_Date, ''' + CONVERT(VARCHAR(20), @EndDate) + ''') >= 0 '
        END

    IF NOT @MonthsID IS NULL OR NOT @YearsID IS NULL     --Between Accounting Periods
        BEGIN
--             SET @sql = @sql + ' AND t.Slu_AW_Months_ID = ' + CONVERT(VARCHAR(20), @MonthsID) +
--                               ' AND t.Slu_AW_Years_ID = ' + CONVERT(VARCHAR(20), @YearsID)
            SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + '''' + ' '
        END

		--V6.4 RL Hide Zero transaction payments that are created by the system!!!!
		SET @sql = @sql + 'AND t.AO_Transactions_ID NOT IN (SELECT AO_Transactions_ID FROM AO_Transactions WHERE Sys_AW_Transaction_Types_ID = 12 And Total_Amount = 0)'

--    SET @sql = @sql + ' ORDER BY t.Document_Date DESC '
    SET @sql = @sql + ' ORDER BY t.Date_Captured DESC, t.AO_Transactions_ID DESC '


    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AO_Transactions_Audit_Trail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AO_Transactions_Audit_Trail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Transactions_Audit_Trail
--Purpose       :Supplier Transactions Audit Trail Report
--Date          :2003/12/15
--Authors       :TB
--Version       :1.0.0
--MODS:         :28/10/04 - Added Accounting Period filter
--V6.4	RL	2018-04-19	:Hide Zero transaction payments that are created by the system!!!!
-------------------------------------------------------------------------------
--EXEC sp_RPT_AO_Transactions_Audit_Trail 1, 1, 118, 0, '2004/07/30 12:00:01 AM', '2004/10/28 11:59:59 PM', 1, 10, 5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Transactions_Audit_Trail]
    (
            @CompanyID int,
            @ChkAllSuppliers int,
            @SupplierID int,
            @ChkDates int,
            @StartDate datetime,
            @EndDate datetime,
            @ChkPeriod int,
            @MonthID tinyint,
            @YearID int
    )
AS

-- SET @CompanyID = 1
-- SET @ChkAllSuppliers = 1
-- SET @SupplierID = 1627
-- SET @ChkDates = 0
-- SET @StartDate = '2003/01/01 12:00:01 AM'
-- SET @EndDate = '2003/11/11 11:59:59 PM'

SET NOCOUNT ON

    DECLARE @sql varchar(7000)

    SET @sql = ' SELECT '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Date_Captured, 121) AS [CalDay], '
    SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
    SET @sql = @sql + ' t.AO_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier], '
    SET @sql = @sql + ' CONVERT(CHAR(10), t.Document_Date, 121) AS [TranDate], '
    SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [TranType], '
    SET @sql = @sql + ' t.Document_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(t.Supplier_Reference, '''') AS [Ref No], '
    SET @sql = @sql + ' ISNULL(t.Comment, '''') AS [Comment], '

--     SET @sql = @sql + ' LEFT(ISNULL(gl.Description, ''''), 20) AS [GL Account], '
--     SET @sql = @sql + ' gl.[Description] AS [GL Account], '
--    SET @sql = @sql + ' ISNULL(glt.Transaction_Code, '''') AS [GLTranType], '
--     SET @sql = @sql + ' gt.AB_Source_Ref AS [Ref No], '
--     SET @sql = @sql + ' gt.AB_Transaction_Date AS [Date], '
--     SET @sql = @sql + ' m.[Description] AS [Month], '
--     SET @sql = @sql + ' y.[Description] AS [Year], '
--     SET @sql = @sql + ' gt.[Description] AS [Description], '
--     SET @sql = @sql + ' gt.AB_Transaction_Amount AS [Amount], '

    SET @sql = @sql + ' ISNULL(t.Trade_Discount_Total, 0) + ISNULL(t.Rebate_Discount_Total, 0) + ISNULL(t.Other_Discount_Total, 0) AS [Discount], '
    SET @sql = @sql + ' t.Net_Amount AS [Amount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [Tax], '
    SET @sql = @sql + ' t.Total_Amount AS [Total], '
    SET @sql = @sql + ' t.Payment_Amount AS [Payment], '
    SET @sql = @sql + ' ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance], '
    SET @sql = @sql + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AO_Transactions t '
    SET @sql = @sql + '      LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '          ON s.AO_Suppliers_ID = t.AO_Suppliers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '
--     SET @sql = @sql + '      LEFT JOIN AB_GL_Transactions gt '
--     SET @sql = @sql + '      	 ON t.AO_Transactions_ID = gt.AB_Transaction_Ref '
--     SET @sql = @sql + '      LEFT JOIN AB_Accounts gl '
--     SET @sql = @sql + '          ON t.AB_Accounts_ID = gl.AB_Accounts_ID '
--     SET @sql = @sql + '      LEFT JOIN Sys_AB_Transaction_Types glt '
--     SET @sql = @sql + '          ON gt.Sys_AB_Transaction_Types_ID = glt.Sys_AB_Transaction_Types_ID '
--     SET @sql = @sql + '      INNER JOIN Slu_AW_Months m '
--     SET @sql = @sql + '      	 ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
--     SET @sql = @sql + '      INNER JOIN Slu_AW_Years y '
--     SET @sql = @sql + '      	 ON t.Slu_AW_Years_ID  = y.Slu_AW_Years_ID '

    SET @sql = @sql +
        ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '   (t.Sys_AW_Transaction_Types_ID = 6 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 8 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 9 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 10 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 11 OR ' +
        '    t.Sys_AW_Transaction_Types_ID = 12) '

--         '   (gt.Sys_AB_Transaction_Types_ID = 5 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 6 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 7 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 8 OR ' +
--         '    gt.Sys_AB_Transaction_Types_ID = 25) '

    IF @ChkAllSuppliers = 0        --Single Supplier Account
        BEGIN
            SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
        END


    IF @ChkDates = 1               --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND t.Document_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND t.Document_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END
    

    IF @ChkPeriod = 1              --Accounting Period
        BEGIN
            SET @sql = @sql + '  AND t.Slu_AW_Months_ID = ' + '''' + CONVERT(varchar(20), @MonthID) + '''' + ' '
            SET @sql = @sql + '  AND t.Slu_AW_Years_ID = ' + '''' + CONVERT(varchar(30), @YearID) + '''' + ' '
        END


		--V6.4 RL Hide Zero transaction payments that are created by the system!!!!
		SET @sql = @sql + 'AND t.AO_Transactions_ID NOT IN (SELECT AO_Transactions_ID FROM AO_Transactions WHERE Sys_AW_Transaction_Types_ID = 12 And Total_Amount = 0)'

    SET @sql = @sql + ' ORDER BY t.Date_Captured ASC '


    EXEC (@sql)


SET NOCOUNT OFF
GO

















GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Get_Supplier_Account_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Get_Supplier_Account_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Get_Supplier_Account_Balance
--Purpose       :Retrieve the latest Supplier Account Balance
--              :
--Parameters    :
--Date          :2018/04/23
--Authors       :RL
--Version       :6.4
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Get_Supplier_Account_Balance]
    (
    	@CompanyID int,
        @SupplierID int,
    	@Balance money OUTPUT
    )

AS

SET NOCOUNT ON

    SET @Balance = 0

    SELECT @Balance =  ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0)
    FROM AO_Transactions
    WHERE AO_Suppliers_ID = @SupplierID AND
          ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
         (Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement Discount
          Sys_AW_Transaction_Types_ID = 8 OR        --Purchase Invoice
          Sys_AW_Transaction_Types_ID = 9 OR        --Purchase Refund
          Sys_AW_Transaction_Types_ID = 10 OR       --Purchase Journal
          Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_Chrono_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_Chrono_Header]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Chrono_Header
--Purpose       :Selects POS Transaction Header Shaped
--Date          :2003/08/09
--Authors       :TB
--Version       :1.0
--MODS          :18/12/03 - Added [TypeID] field for Customer Transaction Search
--              :06/12/04 - Reversed [Customer] field as (Surnames, Firstnames)
--              :06/12/04 - Added @CompanyID filter in WHERE clauses
--              :06/12/04 - Added CASE statement to not calculate GP on PAYMENTS
--V6.4	RL	2018-04-23	:Add GP%
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Chrono_Header]
	(
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

--> Specific Transaction Type
    IF @TransactionTypeID <> 0
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
--                RTRIM(LTRIM(ISNULL(c.Firstnames, '') + ISNULL(' ' + c.Surname, ''))) AS [Customer],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Total_Cost AS [Total Cost],


           CASE WHEN (t.Total_Amount - t.Total_Tax_Amount) <> 0
                THEN CONVERT(    money, (   ((t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost)) / (t.Total_Amount - t.Total_Tax_Amount)  * 100 )  )
                ELSE 0.00
                END AS [GP%],

                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Comment AS [Comment],
                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                a.[Description] AS [Active],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                INNER JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
            ORDER BY t.Transaction_Date DESC
        END

--> ALL Transaction Types
    ELSE
        BEGIN
            SELECT DISTINCT
                t.AS_Transactions_ID AS [ID],
                t.AC_Customers_ID AS [CustomerID],
--                RTRIM(LTRIM(ISNULL(c.Firstnames, '') + ISNULL(' ' + c.Surname, ''))) AS [Customer],
                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Amount AS [Amount],
                t.Total_Discount_Amount AS [Discount],
                t.Total_Tax_Amount AS [VAT],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Payment],
                t.Total_Cost AS [Total Cost],

           CASE WHEN (t.Total_Amount - t.Total_Tax_Amount) <> 0
                THEN CONVERT(    money, (   ((t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost)) / (t.Total_Amount - t.Total_Tax_Amount)  * 100 )  )
                ELSE 0.00
                END AS [GP%],
                
                CASE WHEN t.Sys_AW_Transaction_Types_ID <> 7 AND
                          t.Sys_AW_Transaction_Types_ID <> 18 AND
                          t.Sys_AW_Transaction_Types_ID <> 21 AND
                          t.Sys_AW_Transaction_Types_ID <> 22
                     THEN CONVERT(money,(t.Total_Amount - t.Total_Tax_Amount) - (t.Total_Cost))
                     ELSE 0
                END AS [GP],

                t.Comment AS [Comment],
                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                a.[Description] AS [Active],
               	t.Sys_AW_Transaction_Types_ID AS [TypeID]
            FROM AS_Transactions t
                INNER JOIN AC_Customers c
                    ON t.AC_Customers_ID = c.AC_Customers_ID
                INNER JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                INNER JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (t.Sys_AW_Transaction_Types_ID = 1 or
                  t.Sys_AW_Transaction_Types_ID = 2 or 
                  t.Sys_AW_Transaction_Types_ID = 3 or 
                  t.Sys_AW_Transaction_Types_ID = 4 or 
                  t.Sys_AW_Transaction_Types_ID = 5 or 
                  t.Sys_AW_Transaction_Types_ID = 7 or 
                  t.Sys_AW_Transaction_Types_ID = 15 or 
                  t.Sys_AW_Transaction_Types_ID = 18 or
                  t.Sys_AW_Transaction_Types_ID = 21 or 
            	  t.Sys_AW_Transaction_Types_ID = 22) AND
                  DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
            ORDER BY Transaction_Date DESC
        END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Contract_Pricing]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Contract_Pricing]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Contract_Pricing
--Purpose       :
--Date          :2008/07/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Contract_Pricing]
    (
        @Filter tinyint,
        @CustomerID	int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int        
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' p.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '
    SET @sql = @sql + ' cp.[Description] AS [Product], '
    SET @sql = @sql + ' cp.Product_Code AS [Code], '
    SET @sql = @sql + ' CONVERT(CHAR(10), cp.Start_Date, 121) AS [Start Date], '
    SET @sql = @sql + ' CONVERT(CHAR(10), cp.End_Date, 121) AS [End Date], '
    SET @sql = @sql + ' cp.Unit_Price AS [Unit Price], '
    SET @sql = @sql + ' cp.Discount_Perc AS [Disc %], '
    SET @sql = @sql + ' cp.Discount_Amount AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [Retail], '
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg. Cost], '
    SET @sql = @sql + ' p.On_Hand as [On Hand], '
	SET @sql = @sql + ' MinSaleQty As [MinQty] '
    SET @sql = @sql + ' FROM AC_Contract_Prices cp '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON p.AP_Products_ID = cp.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = cp.AC_Customers_ID '

	IF @CustomerID <> 0 
		BEGIN
			SET @sql = @sql + ' WHERE c.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
		END

    IF @ChkDates = 1    --From/To Dates
        BEGIN
            SET @sql = @sql + '  AND cp.Start_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + '  AND cp.End_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
        END

    IF @Filter = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Customer], [Product], [Start Date] '
        END
    ELSE
    IF @Filter = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product], [Customer], [Start Date] '
        END
    ELSE
    IF @Filter = 2
        BEGIN
            SET @sql = @sql + ' ORDER BY [Code], [Customer], [Start Date] '
        END
    ELSE
    IF @Filter = 3
        BEGIN
            SET @sql = @sql + ' ORDER BY [Start Date], [Customer], [Product] '
        END
    ELSE
    IF @Filter = 4
        BEGIN
            SET @sql = @sql + ' ORDER BY [End Date], [Customer], [Product] '
        END
    


--PRINT @sql

EXEC (@sql)
GO
UPDATE AB_Accounts 
SET [Description] = 'Consignment V.A.T'
Where [Description] like 'Consignment TAX%'
GO
IF NOT EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE [Description] = 'Consignment V.A.T'
	) 
	BEGIN

		IF EXISTS
		(
			SELECT 1
			FROM sysobjects a 
				INNER JOIN syscolumns b 
					ON a.id = b.id
			WHERE
				columnproperty(a.id, b.name, 'isIdentity') = 1 AND
				objectproperty(a.id, 'isTable') = 1 AND
				a.name = 'AB_Control_Accounts'
		)
		BEGIN
			INSERT AB_Control_Accounts
			(	
				Control_Number, 
				[Description], 
				User_Description, 
				AB_Accounts_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID, 
				Control_Type	
			)
			SELECT
				'704',
				'Consignment V.A.T',
				'Consignment V.A.T',
				AB_Accounts_ID,
				GETDATE(),
				1,
				1,
				1,
				0
			FROM AB_Accounts
			WHERE [Description] = 'Consignment V.A.T'			
		END
		ELSE
		BEGIN
			Declare @AB_Control_Accounts_ID smallint

			SELECT @AB_Control_Accounts_ID = MAX(AB_Control_Accounts_ID)
			FROM AB_Control_Accounts

			INSERT AB_Control_Accounts
			(	
				AB_Control_Accounts_ID,
				Control_Number, 
				[Description], 
				User_Description, 
				AB_Accounts_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID, 
				Control_Type	
			)
			SELECT
				@AB_Control_Accounts_ID + 1,
				'704',
				'Consignment V.A.T',
				'Consignment V.A.T',
				AB_Accounts_ID,
				GETDATE(),
				1,
				1,
				1,
				0
			FROM AB_Accounts
			WHERE [Description] = 'Consignment V.A.T'					
		END
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Headers_Unallocated_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Headers_Unallocated_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Headers_Unallocated_Select
--Purpose       :Select Transactions for Customer Catalog, Payments, Unallocated
--Parameters    :
--Date          :2002/01/21
--Authors       :TB
--Version       :1.0.0
--MODS          :28/05/02 - Added [User] to Choice 1 for display in
--              :           Customer Catalog Unallocated Ageing Transactions
--              :25/06/02 - ALTER NEW @Choice = 10 for Customer Catalog Ageing
--              :           1. ORDER BY to t.Transaction_Date DESC
--              :           2. SELECT list columns re-ordered
--              :02/07/02 - ALTER @Choice = 3 for Customer Payments Picklist
--              :           Select ONLY Customer with UNALLOCATED TRANSACTIONS
--              :           using fn_AC_Customer_Has_Outstanding_Transactions
--              :02/07/02 - ALTER @Choice = 10 to include Payment Transactions
--              :03/07/02 - Added @Choice = 11 for Unallocated PAYMENTS Picklist
--              :           Select ONLY Customers with UNALLOCATED PAYMENTS
--              :07/07/02 - Cleaned up @Choice 6,7 & 8
--              :09/07/02 - ALTER @Choice = 10 to same search criteria as ageing
--              :           source from fn_AC_Customer_Ageing_Non_Grouped
--              :10/07/02 - VALIDATE for NULLs (e.g. Customer_Number)
--              :10/07/02 - Modified WHERE clauses to be INCLUSIVE vs EXCLUSIVE
--              :20/07/02 - Added @Choice = 12 for Unallocated JOURNALS Picklist
--              :           Select ONLY Customers with UNALLOCATED JOURNALS
--              :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22 to ALL Options
--              :08/08/02 - Added @Choice = 14 & 15 for Unallocated REFUNDS Picklist
--              :           Select ONLY Customers with UNALLOCATED REFUNDS
--              :24/09/02 - Modified @Now to return MIDNIGHT TONIGHT which caused
--              :           not all transactions to be included for the @Now day
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :           in @Choice 10. This Mod causes an 'multiple step' ADO error
--              :           in Customer Payments used in @Choices 1, 2, 13, 15
--              :10/11/02 - Validate NULL column values for ALL amount columns
--              :           in @Choice 10 because of a 'multiple step' ADO error
--              :04/04/03 - Removed ISNULL validation of the [Description] column
--              :           in option 6, 7 & 8 because DBC in UI does not populate
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--              :25/10/03 - Added filter CUSTOMER PAYMENTS: PickList by Company
--              :           options 3, 10, 11, 12 & 14
--              :27/11/04 - Added CUSTOMER PAYMENT TYPES 21 and 22 for LUMPSUM
--              :           payments in options 2
--              :08/12/04 - Replaced option 10 (Account Balances) with SHAPED sp's
--2004.2.4      :03/06/05 - Added CUSTOMER UNPAID PAYMENT in option 16
--2004.2.4.1    :21/11/05 - Added Centralised Billing filter in Option 6 and
--              :           added ORDER BY [Description] in Option 8
--2004.2.7      :04/04/06 - Removed option 16 - Unpaid Cheques
--2004.4.3      :07/02/09 - Moved CUSTOMER PAYMENTS PickList rs (@Choice = 3)
--              :           to new sp_AC_Customer_Payments_PickList
--2004.4.8      :23/05/10 - Added NEW Option 3 for Unallocated Payments BOTTOM grid
--              :           and EXCLUDED Ageing and INCLUDED ALL Payments transactions
--              :23/05/10 - Changed field order of Options 2,3,13,15 for Unallocated Payments
--              :23/05/10 - Replaced using vw_AS_Transactions with AS_Transactions
--              :           in Options 2,3,13,15 for Unallocated Payments
--2004.5.0      :18/02/11 - Added Customer Ageing AGAIN for Unallocated Payments BOTTOM grid - S Hurly
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Headers_Unallocated_Select]
	(
        @Choice tinyint,
        @CompanyID int,
        @CustomerID int = 0
    )

AS

SET NOCOUNT ON

    DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime



--> (24/09/02) Truncates the decimal of getdate() and add 1 day then
--             this returns midnite tonight '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))



    EXEC sp_AW_Period_Procedures_Select
             @Now,
             @D1 OUTPUT,
             @D2 OUTPUT,
             @D3 OUTPUT,
             @D4 OUTPUT,
             @D5 OUTPUT,
             @D6 OUTPUT,
             @D7 OUTPUT,
             1,
             @CompanyID



--> CUSTOMER PAYMENTS: Unallocated Transactions (EXCLUDING Payments)
--                 NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    IF @Choice = 1
    	SELECT
            t.AS_Transactions_ID AS [ID], 
            t.AC_Customers_ID AS [CustomerID],
            ISNULL(t.Comment, '') AS [Comment],
            t.Total_Amount AS [Balance],
            t.Total_Amount + t.Payment_Amount AS [Old Balance],
            ISNULL(t.Transaction_Number, '') AS [No], 
            t.Total_Amount AS [Amount], 
            t.Payment_Amount AS [Payment], 
            t.Transaction_Date AS [Date], 
            ISNULL(tt.[Description], '') AS [Type],
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
            a.[Current] ,
            a.[30 Days],
            a.[60 Days],
            a.[90 Days],
            a.[120 Days],
            a.[150 Days],
            a.[180+ Days],
            a.[User]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.ID
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18)
    	ORDER BY t.Transaction_Date


--> CUSTOMER UNALLOCATED: Unallocated Payments (ALL Payments)
--  NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    ELSE
    IF @Choice = 2
    	SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
           (Total_Amount + Payment_Amount <> 0) AND
           (Sys_AW_Transaction_Types_ID = 7 OR
            Sys_AW_Transaction_Types_ID = 21 OR
            Sys_AW_Transaction_Types_ID = 22)


--  NEW 2004.4.8 23 MAY 2010 - Copied from @Choice = 1 and removed AGEING
--> CUSTOMER UNALLOCATED: Unallocated Transactions (INCLUDING Payments)
--  NB: ISNULL validation of amount fields cause 'multiple step' ADO error
    ELSE
    IF @Choice = 3
    	SELECT
            t.AS_Transactions_ID AS [ID], 
            t.AC_Customers_ID AS [CustomerID],
            t.Total_Amount AS [Balance],
            t.Total_Amount + Payment_Amount AS [Old Balance],
            t.Transaction_Date AS [Date], 
            ISNULL(t.Transaction_Number, '') AS [No], 
            t.Total_Amount AS [Amount], 
            t.Payment_Amount AS [Payment],
            ISNULL(t.Comment, '') AS [Comment],
            t.Sys_AW_Transaction_Types_ID AS [Type],
        --NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
            a.[Current] ,
            a.[30 Days],
            a.[60 Days],
            a.[90 Days],
            a.[120 Days],
            a.[150 Days],
            a.[180+ Days],
            [User_ID] AS [User]
    	FROM AS_Transactions t
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.ID
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 7 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18 OR
              t.Sys_AW_Transaction_Types_ID = 21 OR
              t.Sys_AW_Transaction_Types_ID = 22)
    	ORDER BY t.Transaction_Date


    ELSE 
    IF @Choice = 4
    	BEGIN
    		SELECT *
            FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
    	END


--> CUSTOMER CATALOG, PAYMENTS, UNALLOCATED: Ageing Totals of ALL Financial TranTypes
    ELSE
    IF @Choice = 5
    	BEGIN
    		SELECT
    			CustomerID,
    			SUM(Payment) AS [Payment],
    			SUM(Amount) AS [Amount],
    			SUM([Current]) AS [Current],
    			SUM([30 Days]) AS [30 Days],
    			SUM([60 Days]) AS [60 Days],
    			SUM([90 Days]) AS [90 Days],
    			SUM([120 Days]) AS [120 Days],
    			SUM([150 Days]) AS [150 Days],
    			SUM([180+ Days]) AS [180+ Days]
     		FROM dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) 
    		GROUP BY CustomerID
    	END


--> CUSTOMER PAYMENTS: Payment Methods
    ELSE
    IF @Choice = 6
    	SELECT Sys_AW_Payment_Methods_ID AS [ID],
               [Description] AS [Method]
    	FROM Sys_AW_Payment_Methods 
    	WHERE Sys_AW_Payment_Methods_ID <> 1 AND
              Sys_AW_Payment_Methods_ID <> 7 AND
              Sys_AW_Payment_Methods_ID <> 8 AND
              Sys_AW_Payment_Methods_ID <> 10 AND
              Sys_AW_Payment_Methods_ID <> 11 AND
              Sys_AW_Payment_Methods_ID <> 13


--> CUSTOMER PAYMENTS: Card Institution
    ELSE
    IF @Choice = 7
       	SELECT Slu_AS_Card_Institutions_ID as [ID],
               [Description]
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]


--> CUSTOMER PAYMENTS: Banks dbc    (Currently not used)
    ELSE
    IF @Choice = 8
       	SELECT Slu_AW_Banks_ID as [ID],
               [Description]
    	FROM Slu_AW_Banks
        ORDER BY [Description]


--> CUSTOMER JOURNALS: Unallocated Transactions (REDUNDANT OLD VERSION)
    ELSE
    IF @Choice = 9
    	SELECT    
    		t.AS_Transactions_ID AS [ID], 
    		t.AC_Customers_ID AS [CustomerID],
    		ISNULL(tt.[Description], '') AS [Type], 
    		ISNULL(t.Comment, '') AS [Comment],
    		t.Total_Amount AS [Balance],
    		t.Total_Amount + t.Payment_Amount AS [Old Balance],
    		ISNULL(t.Transaction_Number, '') AS [No], 
    		t.Total_Amount AS [Amount], 
    		t.Payment_Amount AS [Payment], 
    		t.Transaction_Date AS [Date], 
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    		a.[Current],
    		a.[30 Days],
    		a.[60 Days],
    		a.[90 Days],
    		a.[120 Days],
    		a.[150 Days],
    		a.[180+ Days]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a
                ON t.AS_Transactions_ID = a.ID
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
    	WHERE t.AC_Customers_ID = @CustomerID AND
              t.AW_User_Companies_ID = @CompanyID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR
              t.Sys_AW_Transaction_Types_ID = 4 OR
              t.Sys_AW_Transaction_Types_ID = 5 OR
              t.Sys_AW_Transaction_Types_ID = 7 OR
              t.Sys_AW_Transaction_Types_ID = 15 OR
              t.Sys_AW_Transaction_Types_ID = 18 OR
              t.Sys_AW_Transaction_Types_ID = 21 OR
              t.Sys_AW_Transaction_Types_ID = 22)
    	ORDER BY t.Transaction_Date


--> CUSTOMER CATALOG: Unallocated Ageing Transactions (used in Account Balances tab ONLY)
--> 2004/12/08 Replaced by SHAPE with sp_AS_Shape_Account_Balance_Header AND
--                                    sp_AS_Shape_Account_Balance_Detail
    ELSE
    IF @Choice = 10
    	SELECT
    		t.AS_Transactions_ID AS [ID], 
    		t.AC_Customers_ID AS [CustomerID],
    		ISNULL(tt.[Description], '') AS [Type],
    		t.Transaction_Date AS [Date], 
    		ISNULL(t.Transaction_Number, '') AS [No], 
    		ISNULL(t.Total_Amount, 0) AS [Amount], 
    		ISNULL(t.Payment_Amount, 0) AS [Payment], 
--     		t.Total_Amount AS [Balance],
--     		t.Total_Amount + t.Payment_Amount AS [Old Balance],
       		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
       		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Old Balance],
    		ISNULL(t.Comment, '') AS [Comment],
--NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    		a.[Current] ,
    		a.[30 Days],
    		a.[60 Days],
    		a.[90 Days],
    		a.[120 Days],
    		a.[150 Days],
    		a.[180+ Days],
            a.[User]
    	FROM AS_Transactions t 
            LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
                ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
                ON t.AS_Transactions_ID = a.[ID]
            LEFT JOIN Sys_AW_Transaction_Types tt
                ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    	WHERE t.AW_User_Companies_ID = @CompanyID AND
              t.AC_Customers_ID = @CustomerID AND
              ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
             (t.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
              t.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
              t.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
              t.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
              t.Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
              t.Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
              t.Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
              t.Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
    	ORDER BY t.Transaction_Date         --DESC


--> UNALLOCATED PAYMENTS: --> PickList rs - ONLY Customers with UNALLOCATED PAYMENTS
    ELSE
    IF @Choice = 11
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Payments(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> UNALLOCATED JOURNALS: --> PickList rs - ONLY Customers with UNALLOCATED JOURNALS
    ELSE
    IF @Choice = 12
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Journals(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> CUSTOMER UNALLOCATED: Unallocated JOURNALS
    ELSE
    IF @Choice = 13
    	SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
            ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
            Sys_AW_Transaction_Types_ID = 5


--> UNALLOCATED REFUNDS: --> PickList rs - ONLY Customers with UNALLOCATED REFUNDS
    ELSE
    IF @Choice = 14
    	SELECT
    		AC_Customers_ID AS [ID], 
    		ISNULL(Surname, '') + ISNULL(', ' + FirstNames, '') AS [Name],
    		ISNULL(Customer_Number, '') AS [No] 
    	FROM AC_Customers
    	WHERE AW_User_Companies_ID = @CompanyID AND
              dbo.fn_AC_Customer_Has_Unallocated_Refunds(AC_Customers_ID) = 1
     	ORDER BY [Name]


--> CUSTOMER UNALLOCATED: Unallocated REFUNDS
    ELSE
    IF @Choice = 15
        SELECT    
            AS_Transactions_ID AS [ID], 
            AC_Customers_ID AS [CustomerID],
            Total_Amount AS [Balance],
            Total_Amount + Payment_Amount AS [Old Balance],
            Transaction_Date AS [Date],
            ISNULL(Transaction_Number, '') AS [No], 
            Total_Amount AS [Amount], 
            Payment_Amount AS [Payment],
            ISNULL(Comment, '') AS [Comment]
        FROM AS_Transactions
        WHERE AC_Customers_ID = @CustomerID AND
            AW_User_Companies_ID = @CompanyID AND
            ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
            Sys_AW_Transaction_Types_ID = 4





SET NOCOUNT OFF    
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AC_Customer_Has_Unallocated_Payments]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AC_Customer_Has_Unallocated_Payments]
GO
-------------------------------------------------------------------------------
--Description   :fn_AC_Customer_Has_Unallocated_Payments
--Purpose       :Returns FLAG for Unallocated Customer Payments PickList
--              :    if Customer has UNALLOCATED PAYMENT amounts
--Parameters    :
--Date          :2002/07/03
--Authors       :TB
--Version       :1.0.0
--MODS          :24/07/02 - Added Sys_AW_Transaction_Types_ID 21 & 22
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount to return
--              :           transactions inserted with NULL Total_Amount !!
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AC_Customer_Has_Unallocated_Payments]
	(
        @CustomerID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AC_Customers_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @CustomerID AND
--                      ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                      Total_Amount + Payment_Amount <> 0 AND
                     (Sys_AW_Transaction_Types_ID = 7 OR
                      Sys_AW_Transaction_Types_ID = 21 OR
                      Sys_AW_Transaction_Types_ID = 22)
            )
    
    		SET @Test = 1
    	ELSE	
    		SET @Test = 0
    
    	RETURN @Test
    END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Account_Balance_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Account_Balance_Header]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Account_Balance_Header
--Purpose       :CUSTOMER CATALOG: Unallocated Ageing Transactions (Account Balances tab)
--Date          :2004/12/08
--Authors       :TB
--Version       :1.0
--MODS          :10/03/06 - Added [TypeID] field - What happened to it before !!!!
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Account_Balance_Header]
	(
        @CustomerID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime

    --> MIDNITE tonight
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, GETDATE()), 0, 1)))

    EXEC sp_AW_Period_Procedures_Select
             @Now,
             @D1 OUTPUT,
             @D2 OUTPUT,
             @D3 OUTPUT,
             @D4 OUTPUT,
             @D5 OUTPUT,
             @D6 OUTPUT,
             @D7 OUTPUT,
             1,
             @CompanyID


    SELECT
    	t.AS_Transactions_ID AS [ID], 
    	t.AC_Customers_ID AS [CustomerID],
    	ISNULL(tt.[Description], '') AS [Type],
    	t.Transaction_Date AS [Date], 
    	ISNULL(t.Transaction_Number, '') AS [No], 
    	ISNULL(t.Total_Amount, 0) AS [Amount], 
    	ISNULL(t.Payment_Amount, 0) AS [Payment], 
--     		t.Total_Amount AS [Balance],
--     		t.Total_Amount + t.Payment_Amount AS [Old Balance],
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
		ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Old Balance],
    	ISNULL(t.Comment, '') AS [Comment],
    --NB: DO NOT ADD ANY COLUMNS BEFORE AGEING. HIDEROWS ORDINAL POSITION
    	a.[Current] ,
    	a.[30 Days],
    	a.[60 Days],
    	a.[90 Days],
    	a.[120 Days],
    	a.[150 Days],
    	a.[180+ Days],
        a.[User],
        t.Sys_AW_Transaction_Types_ID AS [TypeID]
    FROM AS_Transactions t 
        LEFT JOIN dbo.fn_AC_Customer_Ageing_Non_Grouped
            ( @CustomerID, @Now, @D1, @D2, @D3, @D4, @D5, @D6, @D7 ) a 
            ON t.AS_Transactions_ID = a.[ID]
        LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.AC_Customers_ID = @CustomerID AND
          ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 AND
         (t.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
          t.Sys_AW_Transaction_Types_ID = 4 OR   --Refund
          t.Sys_AW_Transaction_Types_ID = 5 OR   --Journal
          t.Sys_AW_Transaction_Types_ID = 7 OR   --Payment
          t.Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
          t.Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
          t.Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
          t.Sys_AW_Transaction_Types_ID = 22)    --EFT Payment
    ORDER BY t.Transaction_Date         --DESC



SET NOCOUNT OFF
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Payment_Unallocate]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Payment_Unallocate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Payment_Unallocate
--Purpose       :CURSOR - Reverses Customer Payment Allocations for a specific Payment
--Date          :2018-03-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_Payment_Unallocate]
    (
        @PaymentTranID int,
    	@UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

	--Transaction handled in code
    -----------------------------------------------------------
    --BEGIN TRAN Reverse_Payment
    -----------------------------------------------------------

	DECLARE @Linked_AS_Transactions_ID			Int,
			@Payment_Amount						Decimal(18,2),
			@Allocated_Amount					Decimal(18,2),
			@Amount								Decimal(18,2),
			@ReturnCode							Int,
			@AS_Transactions_Transactions_ID	Int,
			@Transactions_Type_ID				Int,
			@Rev_JRN							Int,
			@Run_Once							Int

	SELECT @ReturnCode = 0
	SELECT @Rev_JRN = 0
	SELECT @Run_Once = 0

	--Check if allocated amount is same as payment amount
	SELECT	@Payment_Amount = Payment_Amount,
			@Transactions_Type_ID = Sys_AW_Transaction_Types_ID
	FROM AS_Transactions
	WHERE AS_Transactions_ID = @PaymentTranID

	IF @Transactions_Type_ID = 4
	BEGIN
--Select 1
		--@PaymentTranID Is Always in the Source_AS_Transactions_ID
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
		AND ISNULL(Destination_AS_Transactions_ID,0) <> 0

		IF @Payment_Amount <> (@Allocated_Amount)
			SELECT @ReturnCode = 2			
	END
	ELSE 
	IF @Transactions_Type_ID = 5
	BEGIN
--Select 2
		SET @Allocated_Amount = 0

		--Destination_AS_Transactions_ID tested with positive and negative
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID

		IF ISNULL(@Allocated_Amount,0) = 0
		BEGIN
--Select 3		
			SELECT @Rev_JRN = 1
			
			--Source_AS_Transactions_ID tested with positive and negative
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0

			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
--Select 4
			IF @Payment_Amount <> (@Allocated_Amount * -1)
				SELECT @ReturnCode = 2
		END
	END
	ELSE 
	IF @Transactions_Type_ID = 7
	BEGIN
--Select 5
		SET @Allocated_Amount = 0
		
		--Destination_AS_Transactions_ID tested with a positive and negative amount
		--Source_AS_Transactions_ID tested with a positive amount
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
		IF ISNULL(@Allocated_Amount,0) = 0
		BEGIN
--Select 6		
			SELECT @Rev_JRN = 1
			
			SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		
			IF @Payment_Amount <> (@Allocated_Amount)
				SELECT @ReturnCode = 2
		END
		ELSE
		BEGIN
--Select 7				
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
		END
	END
	ELSE 
	IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
	BEGIN
--Select 8
		--Destination_AS_Transactions_ID tested with a negative amount. No Positive amount
		--Source_AS_Transactions_ID not found
		SELECT @Allocated_Amount = SUM(ISNULL(Amount,0))
		FROM AS_Transactions_Transactions
		WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
		AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		
		IF @Payment_Amount <> (@Allocated_Amount * -1)
			SELECT @ReturnCode = 2
	END
	ELSE
	BEGIN
--Select 9
		--Scenario not tested
		SELECT @ReturnCode = 2
	END

	IF @ReturnCode = 0
	BEGIN
--Select 10
		IF @Transactions_Type_ID = 4
		BEGIN
--Select 11
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
		END
		ELSE 
		IF @Transactions_Type_ID = 5
		BEGIN
--Select 12
			IF @Rev_JRN = 0
			BEGIN
--Select 13
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
			END
			ELSE
			BEGIN
--Select 14
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID			
				AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
			END
		END
		ELSE 
		IF @Transactions_Type_ID = 7
		BEGIN
--Select 15
			IF @Rev_JRN = 0
			BEGIN
--Select 16
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
				AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
			END
			ELSE
			BEGIN
--Select 17
				DECLARE GetData CURSOR
				FOR
				SELECT AS_Transactions_Transactions_ID, Destination_AS_Transactions_ID, Amount
				FROM AS_Transactions_Transactions
				WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
				AND ISNULL(Destination_AS_Transactions_ID,0) <> 0
			END
		END
		ELSE 
		IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
		BEGIN
--Select 18
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		END
		ELSE
		BEGIN
--Select 19
			DECLARE GetData CURSOR
			FOR
			SELECT AS_Transactions_Transactions_ID, Source_AS_Transactions_ID, Amount
			FROM AS_Transactions_Transactions
			WHERE ISNULL(Source_AS_Transactions_ID,0) <> 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
		END
		
		OPEN GetData

		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		WHILE @@Fetch_Status = 0
		BEGIN
--Select 20
			SELECT @ReturnCode = 1
			
			IF @Transactions_Type_ID = 4
			BEGIN
--Select 21
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE 
			IF @Transactions_Type_ID = 5
			BEGIN
--Select 22
				IF @Rev_JRN = 0
				BEGIN
--Select 23
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
				ELSE
				BEGIN
--Select 24
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @PaymentTranID

					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
			END
			ELSE 
			IF @Transactions_Type_ID = 7
			BEGIN
--Select 25
				IF @Rev_JRN = 0
				BEGIN
--Select 26
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
				END
				ELSE
				BEGIN
--Select 27
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount - @Amount
					WHERE AS_Transactions_ID = @PaymentTranID
				
					UPDATE AS_Transactions
					SET Payment_Amount = Payment_Amount + @Amount
					WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID				
				END
			END
			ELSE 
			IF ((@Transactions_Type_ID = 21) Or (@Transactions_Type_ID = 22))
			BEGIN
--Select 28
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
			ELSE
			BEGIN
--Select 29
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount - @Amount
				WHERE AS_Transactions_ID = @PaymentTranID
			
				UPDATE AS_Transactions
				SET Payment_Amount = Payment_Amount + @Amount
				WHERE AS_Transactions_ID = @Linked_AS_Transactions_ID
			END
--Select 30
			DELETE AS_Transactions_Transactions			
			WHERE AS_Transactions_Transactions_ID = @AS_Transactions_Transactions_ID	

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @PaymentTranID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0
				
			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID
			AND ISNULL(Destination_AS_Transactions_ID,0) = 0

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID

			DELETE AS_Transactions_Transactions			
			WHERE ISNULL(Source_AS_Transactions_ID,0) = 0
			AND ISNULL(Destination_AS_Transactions_ID,0) = @Linked_AS_Transactions_ID

--Select 31
		
		FETCH NEXT FROM GetData INTO @AS_Transactions_Transactions_ID, @Linked_AS_Transactions_ID, @Amount
		END
		CLOSE GetData
		DEALLOCATE GetData
	END
--Select 32
	--When an allocation is done via the Unallocated Payments screen it adds a record to 
	--AS_Transactions_Transactions with a NULL Source_AS_Transactions_ID. Fuck knows why !!!


--	Exec sp_AS_Payment_Unallocate @PaymentTranID, @UserID, @CompanyID


	IF @ReturnCode = 1
	BEGIN
		DELETE AS_Transactions_Transactions
		WHERE ISNULL(Destination_AS_Transactions_ID,0) = @PaymentTranID
	END

--Transaction handled in code		
--IF @ReturnCode = 1
--	COMMIT TRAN Reverse_Payment
--ELSE
--	ROLLBACK TRAN Reverse_Payment

--1 Success
--0 Error
--2 Allocation Amount not same as payment Amount
SET NOCOUNT OFF
RETURN @ReturnCode
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Annual_Budget_Export]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Annual_Budget_Export]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Annual_Budget_Export
--Purpose       :Annual Budget Export
--Parameters    :
--Date          :2011/10/19
--Authors       :TB
--MODS          :
--2004.5.7      :17/01/12 - Added Option to fetch ACTUALS or BUDGET
--RL	V6.4	:2018-05-14 - Changed ID to id. Excel thinks it is a SYLK file if it contains a capital ID 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Annual_Budget_Export]
    (
        @Option tinyint,
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @M1 tinyint,
        @Y1 int,
        @M2 tinyint,
        @Y2 int,
        @M3 tinyint,
        @Y3 int,
        @M4 tinyint,
        @Y4 int,
        @M5 tinyint,
        @Y5 int,
        @M6 tinyint,
        @Y6 int,
        @M7 tinyint,
        @Y7 int,
        @M8 tinyint,
        @Y8 int,
        @M9 tinyint,
        @Y9 int,
        @M10 tinyint,
        @Y10 int,
        @M11 tinyint,
        @Y11 int,
        @M12 tinyint,
        @Y12 int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)

    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @MonthID OUTPUT,
                        @YearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@M1, @Y1)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@M12, @Y12)

    IF @Option = 0
        BEGIN
            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' a.AB_Accounts_ID AS [id], '
            SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Category], '
            SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M1) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y1)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M1) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M2) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y2)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M2) + '], '      
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M3) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y3)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M3) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M4) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y4)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M4) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M5) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y5)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M5) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M6) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y6)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M6) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M7) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y7)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M7) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M8) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y8)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M8) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M9) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y9)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M9) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M10) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y10)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M10) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M11) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y11)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M11) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M12) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y12)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M12) + '] '
        
            SET @sql = @sql + ' FROM AB_Accounts a '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
            SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
            SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
            SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
            SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
            SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
        
            SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '        --Only Income Statement accounts
        
            SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
            SET @sql = @sql + '          b.Sys_AB_I2_ID, '
            SET @sql = @sql + '          b.Sys_AB_I3_ID, '
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            SET @sql = @sql + '          a.Description   '
        END
    ELSE
    IF @Option = 1
        BEGIN
            SET @sql = ' SELECT '
        
            SET @sql = @sql + ' a.AB_Accounts_ID AS [ID], '
            SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Category], '
            SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M1) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y1)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M1) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M2) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y2)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M2) + '], '       
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M3) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y3)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M3) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M4) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y4)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M4) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M5) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y5)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M5) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M6) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y6)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M6) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M7) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y7)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M7) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M8) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y8)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M8) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M9) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y9)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M9) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M10) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y10)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M10) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M11) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y11)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M11) + '], '
        
            SET @sql = @sql + ' ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
            SET @sql = @sql + '     FROM AB_Budgets '
            SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
            SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @M12) + ' AND '
            SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @Y12)
            SET @sql = @sql + ' ) AS [Month ' + CONVERT(CHAR(2),@M12) + '] '
        
            SET @sql = @sql + ' FROM AB_Accounts a '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
            SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
            SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
            SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
            SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
            SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
            SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '
        
            SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
            SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '        --Only Income Statement accounts
        
            SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
            SET @sql = @sql + '          b.Sys_AB_I2_ID, '
            SET @sql = @sql + '          b.Sys_AB_I3_ID, '
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            SET @sql = @sql + '          a.Description   '
        END

EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]
GO					 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Detail_Insert
--Purpose       :INSERTS POS transaction details and UPDATES Product On_Hand
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Details_Select
--              :       and sp_AS_POS_Transaction_Document_Details_Select_Absolute
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Parameters    :NB NB: The last Parameter (@TransactionTypeID) is used to
--              :       determine the sign inserted in the amount fields
--Date          :2002/01/04
--Authors       :TB
--MODS          :26/02/04 - Added SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :28/02/04 - Added [PromotionPrice] parameter
--              :28/02/04 - Added update to Qty_Sold if Promotion Product WAS SOLD
--              :           at the PROMOTION PRICE
--              :05/04/04 - Removed SET @Cost = -(@Cost) if TranType = 4 (Credit Note)
--              :           The Cost must be POSITIVE otherwise Item Cost is positive 
--              :           when multiplying Qty * Cost for a Refund transaction
--              :07/06/04 - Put a space after minus in SET On_Hand = On_Hand - @Qty
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :10/06/08 - Removed UPDATE of ALL RESERVED fields in AP_Products
--2004.4.7      :22/08/09 - Added UPDATE STOCK QTY if @TransactionTypeID = 23 (Stock Transfer)
--2004.4.8      :27/03/10 - Removed redundant vars
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
--V6.2	RL	2015-07-16	:Consignment stock transactions
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017-09-10	:Added Back Order Functionality
--V6.4	RL	2018-05-14	:Fixed Back Order Issues
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Detail_Insert]
    (
		@DocumentDetailsID int = NULL OUTPUT,
		@DocumentID int = NULL,
		@ProductID int = NULL,
		@Qty decimal(9,3) = 0,
		@Cost money = 0,
		@Price money = 0,
		@OriginalPrice money = 0,
		@Discount money = 0,
		@Tax money = 0,
		@TotalAmount money = 0,
		@Commission money = 0,
		@PromotionProductID int = 0,
		@PromotionPrice money = 0,
		@JobRefID int = 0,
        @SerialNo varchar(13) = '',
        @Make varchar(6) = '',
        @Customer varchar(20) = '',
		@DateCaptured datetime = NULL,
		@UserID int = NULL,
		@CompanyID int =  NULL,
		@TDHeader varchar(256) = '',
		@TDDetail varchar(256) = '',
		@ProductBinsID int,
		@BackOrder decimal(9,3) = 0,		
		@OldTransactionTypeID int = NULL,
		@TransactionTypeID int = NULL
    )
AS

SET NOCOUNT ON
	DECLARE @PromoSalesQty				decimal(9,3),
			@IsConsignmentStock			int,
			@CostingMethod				int,
			@Cost_Original				money,
			@Cost_Diff					money,
			@Oppisite_Qty				decimal(9,3),

			@H_Total_Cost				money,
			@H_Amount					money,
			@H_Total_Tax_Amount			money,
			@H_Total_Discount_Amount	money,
			@H_Total_Amount				money,
			@ExistingTransID			int

	IF ISNULL(@ProductBinsID,0) <= 0
		SET @ProductBinsID = 1

	SELECT @BackOrder = ISNULL(@BackOrder,0)

-------------------------------------------------------------------------------
    --> Based on the TransactionType, determine where Qty is to be updated
-------------------------------------------------------------------------------

    --> Invoice
	IF @TransactionTypeID = 3
	BEGIN
		--> Invoice - Check if product sold was consignment stock
		SET @IsConsignmentStock = 0
		EXEC sp_AS_Transaction_Detail_Consignment @ProductID, @Qty, @UserID, @CompanyID, @IsConsignmentStock OUTPUT
		
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
                       
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'INV',			--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	            
	END		

    --> Refund
	IF @TransactionTypeID = 4
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand + @Qty
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Qty,			--@Qty decimal(9,3)
    			'CRN',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int
		    	
		END	
	END
	
    --> Stock Transfer - NEW 2004.4.7
	IF @TransactionTypeID = 23
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'StockTrans',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	            
	END

    --> Consignment Note - NEW 2016.6.2
	IF @TransactionTypeID = 33
	BEGIN
        UPDATE AP_Products
        SET On_Hand = On_Hand - @Qty,
            Last_Sale_Date = getdate()
        WHERE AP_Products_ID = @ProductID
            
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			SELECT @Oppisite_Qty = @Qty * -1
				
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				@ProductBinsID,	--@ProductBinID int,
    			@Oppisite_Qty,	--@Qty decimal(9,3)
    			'StockTrans',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int		    	
		END	
	END


-------------------------------------------------------------------------------
    --> Refund or Sales Order Reversal
	IF @TransactionTypeID = 4 or @TransactionTypeID = 17
	BEGIN
		SET @Qty = -(@Qty)
--            SET @Cost = -(@Cost)    --NB NB NB: DO NOT DO THIS because
--                                    --when multiplying -Qty * -Cost for a Refund transaction
--                                    --the cost amount is POSITIVE reflecting incorrect GP's !!
		SET @Tax = -(@Tax)
		SET @TotalAmount = -(@TotalAmount)
		SET @Commission = -(@Commission)
	END
	ELSE
	BEGIN
		SET @Discount = -(@Discount)
	END
-------------------------------------------------------------------------------


-------------------------------------------------------------------------------
    --> If a Promotion Product WAS SOLD AT the Promotion Price, add to Qty Sold
-------------------------------------------------------------------------------
    IF @TransactionTypeID = 3 OR @TransactionTypeID = 4
    BEGIN
        IF @PromotionProductID > 0
        BEGIN
            IF @Price = @PromotionPrice
            BEGIN
                SELECT @PromoSalesQty = Qty_Sold
                FROM AP_Promotion_Products
                WHERE AP_Promotion_Products_ID = @PromotionProductID
        
                SET @PromoSalesQty = @PromoSalesQty + @Qty
        
                UPDATE AP_Promotion_Products
                SET Qty_Sold = @PromoSalesQty
                WHERE AP_Promotion_Products_ID = @PromotionProductID
            END
        END
    END
-------------------------------------------------------------------------------

	IF @IsConsignmentStock = 1
	BEGIN
		
		SET @Cost_Original = @Cost
		
		SET @CostingMethod = 0
		SELECT @CostingMethod = Control_Index 
		FROM Sys_AW_Options 
		WHERE Control_Name = 'optInventoryValuation' 
		AND Control_Value = 'True'
	
		--0 - Average Cost
		--1	- Last Cost
		--2 - Standard Cost
		IF @CostingMethod IS NULL
			SET @CostingMethod = 0
			
		IF @CostingMethod = 0
		BEGIN
			SELECT @Cost = ISNULL(Average_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END

		IF @CostingMethod = 1
		BEGIN
			SELECT @Cost = ISNULL(Last_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END
		
		IF @CostingMethod = 2
		BEGIN
			SELECT @Cost = ISNULL(Standard_Cost,0)
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID
		END		
	END 

	SELECT @DocumentDetailsID = 0

	IF @TransactionTypeID = 16
	BEGIN
		SELECT @DocumentDetailsID = 0
		
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID AND
			    AP_Products_ID = @ProductID AND
			    --Unit_Cost = @Cost AND
			    Unit_Price = @Price AND
			    Original_Price = @OriginalPrice AND
				Lup_AP_Product_Bins_ID = @ProductBinsID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			Update AS_Transaction_Details
			SET Quantity = Quantity + @Qty,
				Back_Order = Back_Order + @BackOrder,
				Unit_Cost = @Cost,
				Unit_Price = @Price,
				Original_Price = @OriginalPrice,
				Discount_Amount = Discount_Amount + @Discount,
				Tax_Amount = Tax_Amount + @Tax,
				Extended_Amount = Extended_Amount + @TotalAmount
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END
	END

	--If @DocumentDetailsID = 0, Insert will be done later
	IF @TransactionTypeID In (1, 2, 3, 13, 16, 33)
	BEGIN
		IF @BackOrder <> 0 
		BEGIN
			IF @OldTransactionTypeID >= -99
			BEGIN
				EXEC sp_AS_POS_Add_BO_To_SO
											@DocumentID,
											@ProductID,
											@BackOrder,
											@Qty,
											@Cost,
											@Price,
											@OriginalPrice,
											@Discount,
											@Tax,
											@TotalAmount,
											@Commission,
											@PromotionProductID,
											@PromotionPrice,
											@JobRefID,
											@SerialNo,
											@Make,
											@Customer,
											@TDHeader,
											@TDDetail,
											@ProductBinsID,
											@TransactionTypeID,
											@OldTransactionTypeID,
											@UserID,
											@CompanyID
			END

			IF @TransactionTypeID <> 16
				SET @BackOrder = 0

		END
	END

	IF ISNULL(@DocumentDetailsID,0) = 0
	BEGIN
		INSERT AS_Transaction_Details
			(
				AS_Transactions_ID,
				AP_Products_ID,
				Quantity,
				Unit_Cost,
				Unit_Price,
				Original_Price,
				Discount_Amount,
				Tax_Amount,
				Extended_Amount,
				Commission_Amount,
				AP_Promotion_Products_ID,
				AS_Job_References_ID,
				Serial_No,
				Make,
				Customer,
				User_ID,
				AW_User_Companies_ID,
				TDHeader,
				TDDetail,
				Lup_AP_Product_Bins_ID,
				Back_Order
			)
		VALUES
			(
				@DocumentID,
				@ProductID,
				(CASE WHEN @TransactionTypeID = 16 AND  @BackOrder <> 0 THEN 0 ELSE @Qty END),
				@Cost,
				@Price,
				@OriginalPrice,
				@Discount,
				@Tax,
				@TotalAmount,
				@Commission,
				@PromotionProductID,
				@JobRefID,
				@SerialNo,
				@Make,
				@Customer,
				@UserID,
				@CompanyID,
				ISNULL(@TDHeader,''),
				ISNULL(@TDDetail,''),
				@ProductBinsID,
				@BackOrder
			)

		SELECT @DocumentDetailsID = Scope_Identity()
	END
	--V6.3 RL 2017-05-13 Recalc Header Totals
	IF	( 
			@TransactionTypeID = 1 Or		--Quote
			@TransactionTypeID = 2 Or		--Job Card
			@TransactionTypeID = 3 Or		--Tax Invoice
			@TransactionTypeID = 4 Or		--Tax Credit Note
			@TransactionTypeID = 13 Or		--Pro Forma
			@TransactionTypeID = 16 Or		--Sales Order
			@TransactionTypeID = 23 Or		--Stock Transfer
			@TransactionTypeID = 33 Or		--Consignment Note
			@TransactionTypeID = 34 Or		--Consignment Sold
			@TransactionTypeID = 35			--Consignment Returned
		)
	BEGIN
		
		SELECT @H_Total_Cost = SUM((Quantity + Back_Order) * Unit_Cost),
			   @H_Total_Discount_Amount = SUM(Discount_Amount),
			   @H_Amount = SUM(Extended_Amount - Tax_Amount),
			   @H_Total_Tax_Amount = SUM(Tax_Amount),
			   @H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
            Total_Discount_Amount = @H_Total_Discount_Amount,
            Amount = @H_Amount,
            Total_Tax_Amount = @H_Total_Tax_Amount,
            Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
	END

RETURN @DocumentDetailsID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Add_BO_To_SO]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Add_BO_To_SO
--Purpose       :Creates or updates a SO with BO Qty
--Date          :2017/09/10
--Authors       :RL
--V6.4	RL	2018-05-14	:Fixed Back Order Issues
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
    (
		@DocumentID				Int = NULL,
		@ProductID				Int = NULL,
		@Back_Order				Decimal(9,3) = 0,

		@Qty					Decimal(9,3) = 0,
		@Cost					Money = 0,
		@Price					Money = 0,
		@OriginalPrice			Money = 0,
		@Discount				Money = 0,
		@Tax					Money = 0,
		@TotalAmount			Money = 0,
		@Commission				Money = 0,
		@PromotionProductID		Int = 0,
		@PromotionPrice			Money = 0,
		@JobRefID				Int = 0,
        @SerialNo				Varchar(13) = '',
        @Make					Varchar(6) = '',
        @Customer				Varchar(20) = '',
		@TDHeader				Varchar(256) = '',
		@TDDetail				Varchar(256) = '',
		@ProductBinsID			Int,
		@TransactionTypeID		Int,
		@OldTransactionTypeID	Int,		
		@UserID					Int = NULL,
		@CompanyID				Int =  NULL
    )
AS

SET NOCOUNT ON

--Insert Into Temp_Test (Field1) Values ('In sp_AS_POS_Add_BO_To_SO')

	Declare @SO_TransID						Int,
			@CustomerID						Int,
			@Customer_Reference				Varchar(15),
			@NewTransID						Int,
			@Transaction_Number				Varchar(19),

			@NewDiscount					Decimal(18,2),
			@NewTax							Decimal(18,2),
			@NewTotalAmount					Decimal(18,2),
			@TaxRate						Decimal(18,2),
			@chkSOAutoAddPO					Varchar(5),
			@AO_Suppliers_ID				Int,
			@RemoteID						Int,
			@Customer_Name					Varchar(100),
			@PONotes						Varchar(50),
			@AO_Order_Candidates_ID			Int,

			@H_Total_Cost					Decimal(18,2),
			@H_Total_Discount_Amount		Decimal(18,2),
			@H_Amount						Decimal(18,2),
			@H_Total_Tax_Amount				Decimal(18,2),
			@H_Total_Amount					Decimal(18,2),
			@DocumentDetailsID				Int,
			--@DateCaptured					Datetime,
			--@Sys_AW_Transaction_Types_ID	Int,
			@Transaction_Type				Varchar(30),
			@OrigTransaction_Number			Varchar(19),
			@chkSOAutoAddPO_DocType			Varchar(5),
			@Found							Int,
			@SO_CommentID					Int,
			@SO_Comment						Varchar(500),
			@OrigDocCommentID				Int,
			@OrigDocComment					Varchar(500),
			@SO_OrigTransaction_Number		Varchar(19)

	SET @DocumentDetailsID = 0
	SET @SO_TransID = 0
	SET @CustomerID = 0

	IF @TransactionTypeID <> 16
	BEGIN
		SET @SO_TransID = 0

		SELECT	@CustomerID = AC_Customers_ID,
				@Customer_Reference = ISNULL(Customer_Reference,''),
				@OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AS_Transactions_ID = @DocumentID

		SELECT	@SO_TransID = AS_Transactions_ID,
				@SO_CommentID = ISNULL(AW_Comments_ID,0),
				@SO_OrigTransaction_Number = Transaction_Number
		FROM AS_Transactions
		WHERE AC_Customers_ID = @CustomerID AND
			  ISNULL(Customer_Reference,'') = ISNULL(@Customer_Reference,'') AND
			  AW_User_Companies_ID = @CompanyID AND
			  Slu_AW_Active_ID = 1 AND
			  Sys_AW_Transaction_Types_ID = 16 AND 
			  ISNULL(@Customer_Reference,'') <> ''

		IF @SO_TransID <> 0 --Sales Order already exists
		BEGIN

			SELECT @NewTransID = @SO_TransID

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = ISNULL(c.AW_Comments_ID,0),
					@OrigDocComment = ISNULL(c.Comment,'')
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				IF @OrigDocComment NOT Like '%Item was placed on Sales Order for Back Order. Please refer to Sales Order No %'
				BEGIN
					SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @SO_OrigTransaction_Number + ' for details' + '
	' + @OrigDocComment

					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
				END
			END

			--Insert Or update Sales Order transaction comments
			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = LTRIM(RTRIM(ISNULL(Comment,'')))
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			IF @SO_Comment <> '' 
			BEGIN
				IF ( (LEFT(@SO_Comment,5) = 'Quote') OR (LEFT(@SO_Comment,8) = 'Job Card') OR (LEFT(@SO_Comment,11) = 'Tax Invoice') OR (LEFT(@SO_Comment,9) = 'Pro Forma') OR (LEFT(@SO_Comment,16) = 'Consignment Note') )
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + ', ' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
				ELSE
				BEGIN
					SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
' + @SO_Comment))
					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
				END
			END
			ELSE
			BEGIN
				SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number))
				SET @SO_CommentID = NULL
				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment
			END
		END

		IF @SO_TransID = 0
		BEGIN

			If @Transaction_Number = '' OR @Transaction_Number Is Null
				EXEC sp_AW_Get_Next_Transaction_Number 16, 1, @Transaction_Number Output

			SET @SO_Comment = ''
			IF ISNULL(@SO_CommentID ,0) <> 0
			BEGIN
				SELECT @SO_Comment = ISNULL(Comment,'')
				FROM AW_Comments
				WHERE AW_Comments_ID = @SO_CommentID
			END

			SELECT @Transaction_Type = [Description]
			FROM Sys_AW_Transaction_Types
			WHERE Sys_AW_Transaction_Types_ID = @TransactionTypeID

			SET @SO_Comment = LTRIM(RTRIM(@Transaction_Type + ' ' + @OrigTransaction_Number + '
	' + @SO_Comment))
			SET @SO_CommentID = NULL
			EXEC sp_AS_POS_Transaction_Comment_Insert_Update @SO_CommentID OUTPUT, @SO_Comment


			INSERT INTO AS_Transactions
			(
				AC_Customers_ID, 
				AB_Accounts_ID, 
				Sys_AW_Transaction_Types_ID, 
				Transaction_Date, 
				Transaction_Number, 
				Total_Cost, 
				Amount, 
				Total_Tax_Amount, 
				Total_Discount_Amount, 
				Total_Amount, 
				Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				Customer_Reference, 
				Comment, 
				AW_Comments_ID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			SELECT 
				AC_Customers_ID, 
				AB_Accounts_ID, 
				16, 
				Transaction_Date, 
				@Transaction_Number, 
				0,--Total_Cost, 
				0,--Amount, 
				0,--Total_Tax_Amount, 
				0,--Total_Discount_Amount, 
				0,--Total_Amount, 
				0,--Payment_Amount, 
				[Expiry_Date], 
				Version_Number, 
				ISNULL(Customer_Reference,''),
				ISNULL(Comment,''), 
				@SO_CommentID, 
				Lup_AS_Marketing_Indicators_ID, 
				Lup_AW_Stores_ID, 
				Lup_AW_Workstations_ID, 
				Lup_AS_Tills_ID, 
				Lup_AS_Cashiers_ID, 
				Lup_AS_Reps_ID, 
				Slu_AW_Currencies_ID, 
				Old_Sys_AW_Transaction_Types_ID, 
				Cancelled_User_ID, 
				Cancelled_DateTime, 
				Cashed_Up, 
				Day_End, 
				Transmitted, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SET @NewTransID = (SELECT TOP 1 MAX(AS_Transactions_ID) FROM AS_Transactions WHERE Sys_AW_Transaction_Types_ID = 16);

			--Update original document with a reference to the Sales Order just created
			SET @OrigDocCommentID = 0
			SET @OrigDocComment = ''

			SELECT	@OrigDocCommentID = c.AW_Comments_ID,
					@OrigDocComment = c.Comment
			FROM AS_Transactions t
				INNER JOIN AW_Comments c
					ON t.AW_Comments_ID = c.AW_Comments_ID
			WHERE AS_Transactions_ID = @DocumentID

			IF @OrigDocCommentID = 0
			BEGIN
				SET @OrigDocCommentID = NULL
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details'

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

				UPDATE AS_Transactions
				SET AW_Comments_ID = @OrigDocCommentID
				WHERE AS_Transactions_ID = @DocumentID
			END
			ELSE
			BEGIN
				SET @OrigDocComment = 'Item was placed on Sales Order for Back Order. Please refer to Sales Order No ' + @Transaction_Number + ' for details' + '
' + @OrigDocComment

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
			END

		END

	END --@TransactionTypeID <> 16

		IF @Qty = 0
		BEGIN

			--V6.4
			SELECT	@CustomerID = AC_Customers_ID
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @DocumentID

			SELECT @TaxRate = Tax_Rate
			FROM AC_Customers c
				INNER JOIN Sys_AW_Tax_Codes t
					ON c.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
			WHERE AC_Customers_ID = @CustomerID

			SELECT @NewDiscount = 0
			SET @NewTax = 0

--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@CustomerID) + ' @CustomerID')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Back_Order) + ' @Back_Order')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@Price) + ' @Price')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@TaxRate) + ' @TaxRate')

				SELECT @NewTax =  ROUND(( ROUND(@Back_Order * @Price, 2) - @NewDiscount) * (@TaxRate / 100), 2)
				SELECT @NewTotalAmount = ROUND((ROUND(@Back_Order * @Price, 2) - @NewDiscount) + @NewTax, 2)
				
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTax) + ' @NewTax')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewTotalAmount) + ' @NewTotalAmount')
--Insert Into Temp_Test (Field1) Values (CONVERT(Varchar(100),@NewDiscount) + ' @NewDiscount')

		END
		ELSE
		BEGIN

			SELECT @NewDiscount = Round( ((@Discount / @Qty) * @Back_Order),2)

			SET @NewTax = 0

			IF @Tax <> 0
			BEGIN

				SELECT @TaxRate = ROUND( (@Tax / (@TotalAmount - @Tax) * 100) ,0)

				SELECT @NewTax =  ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) * (@TaxRate / 100) ,2)

				SELECT @NewTotalAmount = ROUND( ( ROUND( (@Back_Order * @Price) ,2) - @NewDiscount) + @NewTax ,2)

			END
		END

		--Update Sales Order detail record with new quantity
		SELECT @DocumentDetailsID = AS_Transaction_Details_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @SO_TransID AND
			    AP_Products_ID = @ProductID AND
			    --Unit_Cost = @Cost AND
			    Unit_Price = @Price AND
			    Original_Price = @OriginalPrice AND
				Lup_AP_Product_Bins_ID = @ProductBinsID
		
		IF ISNULL(@DocumentDetailsID,0) <> 0
		BEGIN
			Update AS_Transaction_Details
			SET Quantity = Quantity,
				Back_Order = Back_Order + @Back_Order,
				Unit_Cost = @Cost,
				Unit_Price = @Price,
				Original_Price = @OriginalPrice,
				Discount_Amount = Discount_Amount + @Discount,
				Tax_Amount = Tax_Amount + @Tax,
				Extended_Amount = Extended_Amount + @TotalAmount
			WHERE AS_Transaction_Details_ID = @DocumentDetailsID
		END

		--Insert detail record into Sales order
		IF @DocumentDetailsID = 0
		BEGIN
		
			--V6.4
			--SELECT @NewTransID = @SO_TransID		
			--V6.4
			--IF ISNULL(@NewTransID,0) = 0
				--SELECT @NewTransID = @DocumentID
			
			INSERT AS_Transaction_Details
				(
					AS_Transactions_ID,
					AP_Products_ID,
					Quantity,
					Back_Order,

					Unit_Cost,
					Unit_Price,
					Original_Price,
					Discount_Amount,
					Tax_Amount,
					Extended_Amount,
					Commission_Amount,

					AP_Promotion_Products_ID,
					AS_Job_References_ID,
					Serial_No,
					Make,
					Customer,
					User_ID,
					AW_User_Companies_ID,
					TDHeader,
					TDDetail,
					Lup_AP_Product_Bins_ID
				)
			VALUES
				(
					@NewTransID,
					@ProductID,
					0,	--Qty will always be zero because it is created from another document -- @Qty
					@Back_Order,
					
					ISNULL(@Cost,0),
					ISNULL(@Price,0),
					ISNULL(@OriginalPrice,0),
					ISNULL(@NewDiscount,0),
					ISNULL(@NewTax,0),
					ISNULL(@NewTotalAmount,0),
					NULL,

					@PromotionProductID,
					@JobRefID,
					@SerialNo,
					@Make,
					@Customer,
					@UserID,
					@CompanyID,
					ISNULL(@TDHeader,''),
					ISNULL(@TDDetail,''),
					@ProductBinsID
				)

			SELECT @DocumentDetailsID = Scope_Identity()
		END

		SELECT @H_Total_Cost = SUM((Quantity + @Back_Order) * Unit_Cost),
				@H_Total_Discount_Amount = SUM(Discount_Amount),
				@H_Amount = SUM(Extended_Amount - Tax_Amount),
				@H_Total_Tax_Amount = SUM(Tax_Amount),
				@H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @NewTransID
		
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
			Total_Discount_Amount = @H_Total_Discount_Amount,
			Amount = @H_Amount,
			Total_Tax_Amount = @H_Total_Tax_Amount,
			Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @NewTransID
	


IF @OldTransactionTypeID <> -88
BEGIN		
	SET @chkSOAutoAddPO = '0'

	SELECT @chkSOAutoAddPO = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOAutoAddPO'
		--Add to purchase orders
	IF @chkSOAutoAddPO = '1'
	BEGIN
	
		SET @chkSOAutoAddPO_DocType = '0'

		IF @TransactionTypeID = 1
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOQuote'
		END

		IF @TransactionTypeID = 2
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOJobcard'
		END

		IF @TransactionTypeID = 3
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOInvoice'
		END

		IF @TransactionTypeID = 13
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOProForma'
		END

		IF @TransactionTypeID = 16
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOSalesOrder'
		END

		IF @TransactionTypeID = 33
		BEGIN
			SELECT @chkSOAutoAddPO_DocType = Control_Value
			FROM Sys_AW_Options
			WHERE Control_Name = 'chkSOPromtBOConsignment'
		END

		IF @chkSOAutoAddPO_DocType = '1'
		BEGIN

			SET @AO_Suppliers_ID = 1
				
			SELECT TOP 1 @AO_Suppliers_ID = s.AO_Suppliers_ID
			FROM AP_Products_Suppliers ps
				INNER JOIN AO_Suppliers s
					ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
			WHERE ps.AP_Products_ID = @ProductID AND
				  ps.Slu_AW_Active_ID = 1 AND
				  s.Slu_AW_Active_ID = 1 And
				  GETDATE() Between ps.[Start_Date] And '2999-01-01'
				
			SET @RemoteID = 0
				
			SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
			FROM AW_Remote_Access
			WHERE AW_User_Companies_ID = @CompanyID AND
				  Default_Connection = 1

			IF @CustomerID = 0
			BEGIN
				SELECT	@CustomerID = AC_Customers_ID
				FROM AS_Transactions
				WHERE AS_Transactions_ID = @DocumentID
			END

			SELECT @Customer_Name = Surname
			FROM AC_Customers
			WHERE AC_Customers_ID = @CustomerID
		
   			SELECT @PONotes = Notes
    		FROM AO_Order_Candidates
    		WHERE AP_Products_ID = @ProductID AND
    			  AO_Suppliers_ID = @AO_Suppliers_ID AND
    			  AW_User_Companies_ID = @CompanyID

			SELECT @PONotes = ISNULL(@PONotes,'')

			IF @PONotes = ''
			BEGIN
				SET @PONotes = LEFT('Back Order for ' + @Customer_Name,50)
			END
			ELSE
			BEGIN
				
				SELECT @Found = 0
				SELECT @Found = CHARINDEX(@Customer_Name,@PONotes)

				IF @Found = 0
				BEGIN
					SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)
				END				
				
				SET @PONotes = LEFT(@PONotes + LEFT(' / ' + @Customer_Name,50),50)

			END
								
			EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @Back_Order, @PONotes, @UserID ,@UserID , @CompanyID, @RemoteID
		END
	END
END
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Comment_Insert_Update
--Purpose       :Creates or updates Document's transaction comment
--Date          :2018/09/27
--Authors       :EB
--V6.4	EB	2018-09-27	:Fixed Back Order Issues
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Transaction_Comment_Insert_Update]
	(
		@CommentID int OUTPUT,	
		@Comment varchar(500)
	)

AS

	SET NOCOUNT ON

	IF (@CommentID IS NULL AND @Comment <> '')
	BEGIN
	
		INSERT AW_Comments
        (
            Sys_AT_Actor_Types_ID,
            Comment
        ) 
        VALUES
        (
            -7,
            @Comment
        )

		SELECT @CommentID = Scope_Identity()
		
	END
	ELSE IF (EXISTS(SELECT TOP 1 1 FROM AW_Comments WHERE AW_Comments_ID = @CommentID AND Comment <> @Comment))
	BEGIN
	
		INSERT AW_Comments
        (
            Sys_AT_Actor_Types_ID,
            Comment
        ) 
        VALUES
        (
            -7,
            @Comment
        )

		SELECT @CommentID = Scope_Identity()
		
	END
	ELSE
	BEGIN
		UPDATE AW_Comments
        SET Sys_AT_Actor_Types_ID = -7,
			Comment = @Comment
		WHERE AW_Comments_ID = @CommentID
	END
	
	SET NOCOUNT OFF
GO

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------

IF NOT EXISTS
    (
        SELECT AA_Release_ID
        FROM AA_Release
        WHERE Release = '2018.6.4'
    )
    BEGIN
        INSERT AA_Release
            (
                Release,
                Updated_by			  
            )
        VALUES
            (
                '2018.6.4',
                'Download'
            )
    END

GO
