
------------------------------------------------------------------------------
-- ADVANTAGE 2004.6.0.0100
-- Includes V5.9 Hot Fix
-- NEW OPTIONS, LOOKUPS and APPLICATIONS
-- 2014-11-03
------------------------------------------------------------------------------


-- V5.9 DB Fix 1 And 2
Update AS_Transactions_Address_Detail
Set AC_Customers_ID = AW_User_Companies_ID
Where AC_Customers_ID = 1
And AW_User_Companies_ID <> 1
Go
Update AS_Transactions_Address_Detail
Set AW_User_Companies_ID = 1
Go
Update AS_Transactions_Address
Set AW_User_Companies_ID = 1
GO

--5.9 Fix 11
/****** Object:  StoredProcedure [dbo].[sp_AS_POS_CustomerID_Select]    Script Date: 07/08/2013 22:19:40 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_CustomerID_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_CustomerID_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_CustomerID_Select
--Purpose       :Fetch ONE Customer for a CustomerID
--Date          :2010/03/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' a.Surname AS [Name], '
    SET @sql = @sql + ' a.Firstnames AS [FirstNames], '
    SET @sql = @sql + ' a.Cell_No AS [CellNo], '
    SET @sql = @sql + ' a.Street_Address AS [StreetAddress], '

    SET @sql = @sql + ' a.City AS [City], '
    SET @sql = @sql + ' a.Initials AS [Initials], '
    SET @sql = @sql + ' a.Tax_Number AS [TaxNumber], '
    SET @sql = @sql + ' a.Suburb AS [Suburb], '
    SET @sql = @sql + ' a.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' a.Home_Tel_No AS [HomeTelNo], '
    SET @sql = @sql + ' ISNULL(a.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '         SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0)) '
    SET @sql = @sql + '         FROM AS_Transactions h '
    SET @sql = @sql + '         WHERE h.AC_Customers_ID = a.AC_Customers_ID AND '
    SET @sql = @sql + '               ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND '
    SET @sql = @sql + '              (h.Sys_AW_Transaction_Types_ID = 3 OR '      --Invoice
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 4 OR '      --Refund
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 5 OR '      --Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 7 OR '      --Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 15 OR '     --Interest Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 18 OR '     --Settlement Discount
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 21 OR '     --Back Office Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 22) '       --EFT Payment
    SET @sql = @sql + '         ), 0) AS [AccountBalance], '

    SET @sql = @sql + ' a.Work_Email AS [WorkEmail], '
    SET @sql = @sql + ' a.Notes AS [Notes], '
    SET @sql = @sql + ' a.Sys_AC_Account_Status_ID AS [AccountStatusID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Types_ID AS [CustomerTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID], '
    SET @sql = @sql + ' s.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ct.[Description] AS [CustomerType], '
    SET @sql = @sql + ' g.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' a.[User_ID] AS [UserID], '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' -1 as [ActorTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Discount_Categories_ID, '
    SET @sql = @sql + ' a.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate], '
    SET @sql = @sql + ' a.Slu_AW_Credit_Terms_ID AS [TermsID], '
    SET @sql = @sql + ' e.Terms_Value AS [TermsValue], '
    SET @sql = @sql + ' f.[Description] AS [AccountType], '
    SET @sql = @sql + ' a.Sys_AC_Account_Types_ID AS [AccountTypeID], '
    SET @sql = @sql + ' a.AW_YesNo_Net_Billing_ID AS [NetBilling], '
    SET @sql = @sql + ' a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder], '
    SET @sql = @sql + ' a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling], '
    SET @sql = @sql + ' a.Lup_AC_Markup_Categories_ID AS [CostPlusCategory], '
    SET @sql = @sql + ' a.Delivery_Post_Code AS [DelPostCode], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Credit_Limit AS [OverrideLimit], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Overdue AS [OverrideOverdue], '
    SET @sql = @sql + ' a.AW_YesNo_Apply_Product_Levy AS [CustomerApplyLevy], '           
    SET @sql = @sql + ' a.AW_YesNo_Change_Doc_Details AS [ChangeDocDetails], '       


    SET @sql = @sql + ' ISNULL(Surname, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Suburb, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + City, '''') AS [FullName] '

    SET @sql = @sql + ' FROM AC_Customers a '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions b '
    SET @sql = @sql + '         ON a.AC_Customers_ID = b.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Comments c '
    SET @sql = @sql + '         ON c.AW_Comments_ID = b.AW_Comments_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Types ct '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '         ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Credit_Terms e '
    SET @sql = @sql + '         ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Types f '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Groups g '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + ' WHERE a.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' AND '
    SET @sql = @sql + '       a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.Slu_AW_Active_ID = 1 '

EXEC (@sql)
--Select @sql
SET NOCOUNT OFF
GO


--v5.9 Fix 15
/****** Object:  StoredProcedure [dbo].[sp_AS_Transactions_Address_Insert]    Script Date: 07/15/2013 03:22:47 ******/
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

-------------------------------------------------------------------------------
--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
------------------------------------------------------------------------------- 
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(50),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@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

--    SELECT 
--		@AC_Customers_ID = AC_Customers_ID,
--		@User_ID = User_ID,
--		@Company_ID = AW_User_Companies_ID
--	FROM AS_Transactions
--	WHERE AS_Transactions_ID = @AS_Transactions_ID

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

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	

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

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


--V5.9 Fix 35
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
-------------------------------------------------------------------------------

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
		SET @sql = @sql + ' RTRIM(LTRIM(a.Surname)) + ISNULL('', '' + A.Initials, '''') + '' / '' + IsNull(A.Firstnames,'''') AS [CurrentInvName], '
	ELSE
		SET @sql = @sql + ' RTRIM(LTRIM(A.Surname)) + ISNULL('', '' + A.Initials, '''') AS [CurrentInvName], '	

	IF @WhichAddress = 0
		BEGIN
			SET @sql = @sql + ' ISNULL(a.Post_Box, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(a.Post_Office, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(a.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(a.Post_Code, '''') AS [CurrentInvPostCode], '
		END	
	ELSE
		BEGIN
			SET @sql = @sql + ' ISNULL(a.Street_Address, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(a.Suburb, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(a.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(a.Street_Post_Code, '''') AS [CurrentInvPostCode], '	
		END
		
    SET @sql = @sql + ' ISNULL(a.Tax_Number, '''') AS [TaxNumber], '
	SET @sql = @sql + ' ISNULL(a.Delivery_Address, '''') AS [CurrentDeliverAddress], '
	SET @sql = @sql + ' ISNULL(a.Delivery_Suburb, '''') AS [CurrentDeliverSuburb], '
	SET @sql = @sql + ' ISNULL(a.Delivery_City, '''') AS [CurrentDeliverCity], '
	SET @sql = @sql + ' ISNULL(a.Delivery_Post_Code, '''') AS [CurrentDeliverPostCode] '

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

SET NOCOUNT OFF
GO


--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--V6.0
--1 fn_AW_Ping_Remote_DataSource
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AW_Ping_Remote_DataSource]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AW_Ping_Remote_DataSource]
GO
-----------------------------------------------------------------------------
--Description   :dbo.fn_AW_Ping_Remote_DataSource
--Purpose       :Returns SCALAR bit if DataSource Access failure/success
--Funtionality  :    0 = Success, 1 = Failure
--Notes         :-n Count    - specifies the number of Echo Request messages sent. Default = 4 (4 messages)
--              :-w Timeout  - specifies time in milliseconds to wait for Echo Reply message. Default = 4000 (4 seconds)
--Date          :2009/09/11
--Authors       :TB
--MODS          :
--RL	V6.0	:2014-04-10 - Enhanced MSSQL instance handeling
-----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AW_Ping_Remote_DataSource]
	(
        @DataSource varchar(50),
        @Timeout int
	)

RETURNS bit

AS

	BEGIN	
    	DECLARE @RetCode bit,
                @CmdTxt varchar(100),
                @Pos	Int

        SET @RetCode = 1

		SET @Pos = 0
		SELECT @Pos = CHARINDEX('\', @DataSource)

		IF @Pos <> 0
		BEGIN
			SELECT @DataSource = SUBSTRING(@DataSource,0,@Pos)
		END

        SET @CmdTxt = 'ping -n 1 -w ' + CONVERT(varchar(4), @Timeout) + ' ' + ltrim(rtrim(@DataSource))
        EXEC @RetCode = master..xp_cmdshell @CmdTxt, no_output

	    RETURN @RetCode    
    END
GO

--2 sp_AB_Select_Accounts
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Accounts]
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Accounts
--Functionality :Returns Account Info
--Parameters    :
--Date          :2013/10/28
--Authors       :RL
--Version       :5.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Select_Accounts]
AS

SET NOCOUNT ON

	SELECT ac.AB_Accounts_ID AS [ID],
		   IsNull(ac.Description,'') AS [Account_Name],
		   at.Description AS [Account_Status],
		   uc.Company_Name As [Company_Name]
	FROM AB_Accounts ac
	INNER JOIN Slu_AW_Active at
	ON ac.Slu_AW_Active_ID = at.Slu_AW_Active_ID
	Inner Join AW_User_Companies uc
	On ac.AW_User_Companies_ID = uc.AW_User_Companies_ID 	
	ORDER BY IsNull(ac.Description,'') ASC

SET NOCOUNT OFF
GO

--3 sp_AC_Check_Cellphone
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Check_Cellphone]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Check_Cellphone]
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Check_Cellphone
--Purpose       :Format Cellphone Numbers
--Date          :2012-10-01
--Authors       :RGL
--MODS          :
--RL	V6.0	:2014-04-10 Added garbage removal and formating
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Check_Cellphone]
    (
        @intCountryID           int,
        @intCustomerID          int,        
        @strCellphone	        varchar(20),
        @strCellphone_Formated	varchar(20)OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @strCountry_Code varchar(5),
            @strFirst_2      varchar(2),
            @strCell_Code	 varchar(2)
    
    Set @strCountry_Code = ''
    Set @strCell_Code = ''
    Set @strCellphone_Formated = ''
    Set @strCellphone = Ltrim(Rtrim(@strCellphone))
    Set @strCellphone = Replace(@strCellphone,'   ','')
    Set @strCellphone = Replace(@strCellphone,'  ','')
    Set @strCellphone = Replace(@strCellphone,' ','')
    Set @strCellphone = Replace(@strCellphone,'-','')
    Set @strCellphone = Replace(@strCellphone,'(','')
    Set @strCellphone = Replace(@strCellphone,')','')
   
    IF (@intCustomerID <> -1 AND @intCustomerID <> 0) 
    BEGIN
      Select @intCountryID = Slu_AW_Countries_ID
      From Ac_Customers
      Where AC_Customers_ID = @intCustomerID   
    
      SELECT @strCountry_Code = Country_Dialing_Code
      FROM Slu_AW_Countries
      WHERE Slu_AW_Countries_ID = @intCountryID    		
    END

	IF @strCountry_Code = ''
	BEGIN
		SELECT @strCountry_Code = Control_Value
		FROM Sys_AW_Options 
		WHERE Control_Name = 'txtCountryRegionCode'
	
		SELECT @intCountryID = Slu_AW_Countries_ID
		FROM Slu_AW_Countries
		WHERE IsNull(Country_Dialing_Code,'') = @strCountry_Code    		
	END
	
	IF @strCountry_Code = ''
	BEGIN		
		Set @intCountryID = 193
		
		SELECT @strCountry_Code = Country_Dialing_Code
		FROM Slu_AW_Countries
		WHERE Slu_AW_Countries_ID = @intCountryID    
	END

	IF Left(@strCellphone,5) = '00270'
		SET @strCellphone = Substring(@strCellphone,6,20)
		
	IF Left(@strCellphone,4) = '+270'
		SET @strCellphone = Substring(@strCellphone,4,20)
		
	IF Left(@strCellphone,4) = '0027'
		SET @strCellphone = Substring(@strCellphone,5,20)

	IF Left(@strCellphone,3) = '+27'
		SET @strCellphone = Substring(@strCellphone,4,20)

	IF Left(@strCellphone,3) = '027'
		SET @strCellphone = Substring(@strCellphone,4,20)

	IF Left(@strCellphone,2) = '27'
		SET @strCellphone = Substring(@strCellphone,3,20)

	IF Left(@strCellphone,1) <> '0'
		SET @strCellphone = '0' + @strCellphone
		
    SELECT @strFirst_2 = Substring(@strCellphone,1,2)
   
    SELECT @strCell_Code = Mobile_Dialing_Code
    FROM Slu_AW_Countries_Mobile
    WHERE Slu_AW_Countries_ID = @intCountryID
    AND Mobile_Dialing_Code = @strFirst_2
       
	IF @strCountry_Code != ''
	BEGIN   
		IF @strCell_Code != ''
		BEGIN
			IF Len(@strCellphone) = 10
			BEGIN
				SET @strCellphone_Formated = @strCountry_Code + Right(@strCellphone,9)
			END	
		END          
	END
    
    SELECT @strCellphone_Formated
    
SET NOCOUNT OFF
GO

--4 Moved to bottom of script
--5 sp_AO_Select_Filtered_Products
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(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) AS [Job Reserved], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 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

--6 sp_AO_Select_Suppliers
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Suppliers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Suppliers]
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers
--Functionality :Returns Supplier Info
--Parameters    :
--Date          :2013/10/28
--Authors       :RL
--Version       :5.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Suppliers]
AS

SET NOCOUNT ON

	SELECT AO_Suppliers_ID AS [ID],
		   Supplier_Name AS [Supplier_Name],
		   a.Description AS [Supplier_Status],
		   uc.Company_Name As [Company_Name]
	FROM AO_Suppliers s
	INNER JOIN Slu_AW_Active a
	ON s.Slu_AW_Active_ID = a.Slu_AW_Active_ID
	Inner Join AW_User_Companies uc
	On s.AW_User_Companies_ID = uc.AW_User_Companies_ID 	
	ORDER BY Supplier_Name ASC

SET NOCOUNT OFF
GO

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

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Redundant_Products
--Purpose       :SELECT Redundant UNUSED Products with ZERO STOCK in target DB
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
--2004.5.7 RGL	: 2012-11-01 Exclude levy Products
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Redundant_Products]
	(
        @CompanyID int
	)
AS

SET NOCOUNT ON

        SELECT a.AP_Products_ID AS [ProductID]
        FROM AP_Products a
            FULL OUTER JOIN AS_Transaction_Details b
                ON a.AP_Products_ID = b.AP_Products_ID
            FULL OUTER JOIN AO_GRV_Details c
                ON a.AP_Products_ID = c.AP_Products_ID
            FULL OUTER JOIN AO_Order_Details d
                ON a.AP_Products_ID = c.AP_Products_ID
        WHERE a.AW_User_Companies_ID = 1 AND
              b.AP_Products_ID IS NULL AND
              c.AP_Products_ID IS NULL AND
              d.AP_Products_ID IS NULL AND
              a.On_Hand = 0 AND
              a.Slu_AW_YesNo_Levy_Item = 0 AND
              IsNull(a.Slu_AW_YesNo_Levy_Item,0) = 0

SET NOCOUNT OFF
GO

--8 sp_AS_POS_Customers_Select
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Customers_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Customers_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_Select
--Purpose       :POS Customer Lookup by filter arguments
--Functionality :Searches: Name, Trade/First Name, CellNo, WorkTelNo, HomeTelNo
--              :          Comment, Notes
--Parameters    :
--Date          :2002/04/09
--Authors       :TB
--MODS          :09/09/02 - Inserted ActiveID to SELECT ONLY Active Customers
--              :23/09/02 - Added Search on FirstNames filter
--              :30/12/02 - Added Search on Asset No in AS_Transactions.Comment
--              :           and CellNo, WorkTelNo, HomeTelNo from the VIEW
--              :03/02/03 - Added Search on text in AW_Comments.Comment
--              :29/10/05 - Commented the not yet implemented JOIN AC_Assets
--2004.3.7      :24/07/07 - Reworked as DYNAMIC sp to improve performance and
--              :           ELIMINATED using vw_AS_POS_Customers_Select
--              :24/07/07 - Replaced @Filter* input parameter NULL initialization
--              :           with NULLSTRING ('') initialization
--              :25/07/07 - Added new [CostPlusBilling] field
--              :25/07/07 - Added new [CostPlusCategory] field
--              :04/08/07 - Re-Ordered SELECT SEQUENCE in Customers grid replaced
--              :           TaxNumber and Suburb with CellNo and StreetAddress
--              :17/08/07 - Added new [TermsID] field for Promotions !!
--2004.3.8      :20/06/08 - Added Delivery_Post_Code AS [DelPostCode]
--2004.4.5      :13/06/09 - Added new [OverrideLimit] and [OverrideOverdue] field
--2004.4.8      :26/04/10 - Added new [FullName] field
--RL	V6.0	:Added FirstNames to order by
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Customers_Select]
	(    
    	 @CompanyID int,
    	 @Filter1 varchar(50) = '',
    	 @Filter2 varchar(50) = '',
    	 @Filter3 varchar(50) = ''
	)
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB
    SET @sql = @sql + ' a.Surname AS [Name], '
    SET @sql = @sql + ' a.Firstnames AS [FirstNames], '
    SET @sql = @sql + ' a.Cell_No AS [CellNo], '
    SET @sql = @sql + ' a.Street_Address AS [StreetAddress], '

    SET @sql = @sql + ' a.City AS [City], '
    SET @sql = @sql + ' a.Initials AS [Initials], '
    SET @sql = @sql + ' a.Tax_Number AS [TaxNumber], '
    SET @sql = @sql + ' a.Suburb AS [Suburb], '
    SET @sql = @sql + ' a.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' a.Home_Tel_No AS [HomeTelNo], '
    SET @sql = @sql + ' ISNULL(a.Credit_Limit, 0) AS [CreditLimit], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '         SELECT SUM(ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0)) '
    SET @sql = @sql + '         FROM AS_Transactions h '
    SET @sql = @sql + '         WHERE h.AC_Customers_ID = a.AC_Customers_ID AND '
    SET @sql = @sql + '               ISNULL(h.Total_Amount, 0) + ISNULL(h.Payment_Amount, 0) <> 0 AND '
    SET @sql = @sql + '              (h.Sys_AW_Transaction_Types_ID = 3 OR '      --Invoice
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 4 OR '      --Refund
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 5 OR '      --Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 7 OR '      --Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 15 OR '     --Interest Journal
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 18 OR '     --Settlement Discount
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 21 OR '     --Back Office Payment
    SET @sql = @sql + '               h.Sys_AW_Transaction_Types_ID = 22) '       --EFT Payment
    SET @sql = @sql + '         ), 0) AS [AccountBalance], '

    SET @sql = @sql + ' a.Work_Email AS [WorkEmail], '
    SET @sql = @sql + ' a.Notes AS [Notes], '
    SET @sql = @sql + ' a.Sys_AC_Account_Status_ID AS [AccountStatusID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Types_ID AS [CustomerTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Customer_Groups_ID AS [CustomerGroupID], '
    SET @sql = @sql + ' s.[Description] AS [AccountStatus], '
    SET @sql = @sql + ' ct.[Description] AS [CustomerType], '
    SET @sql = @sql + ' g.[Description] AS [CustomerGroup], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' a.[User_ID] AS [UserID], '
    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' -1 as [ActorTypeID], '
    SET @sql = @sql + ' a.Lup_AC_Discount_Categories_ID, '
    SET @sql = @sql + ' a.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(tc.Tax_Rate, 0) AS [CustTaxRate], '
    SET @sql = @sql + ' a.Slu_AW_Credit_Terms_ID AS [TermsID], '
    SET @sql = @sql + ' e.Terms_Value AS [TermsValue], '
    SET @sql = @sql + ' f.[Description] AS [AccountType], '
    SET @sql = @sql + ' a.Sys_AC_Account_Types_ID AS [AccountTypeID], '
    SET @sql = @sql + ' a.AW_YesNo_Net_Billing_ID AS [NetBilling], '
    SET @sql = @sql + ' a.AW_YesNo_Purchase_Order_ID AS [PurchaseOrder], '
    SET @sql = @sql + ' a.AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling], '
    SET @sql = @sql + ' a.Lup_AC_Markup_Categories_ID AS [CostPlusCategory], '
    SET @sql = @sql + ' a.Delivery_Post_Code AS [DelPostCode], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Credit_Limit AS [OverrideLimit], '
    SET @sql = @sql + ' a.AW_YesNo_Override_Overdue AS [OverrideOverdue], '
    SET @sql = @sql + ' a.AW_YesNo_Apply_Product_Levy AS [CustomerApplyLevy], '           
    SET @sql = @sql + ' a.AW_YesNo_Change_Doc_Details AS [ChangeDocDetails], '       

    SET @sql = @sql + ' ISNULL(Surname, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Firstnames, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + Suburb, '''') + '
    SET @sql = @sql + ' ISNULL(''  '' + City, '''') AS [FullName] '

    SET @sql = @sql + ' FROM AC_Customers a '
    SET @sql = @sql + '     LEFT JOIN AS_Transactions b '
    SET @sql = @sql + '         ON a.AC_Customers_ID = b.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Comments c '
    SET @sql = @sql + '         ON c.AW_Comments_ID = b.AW_Comments_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Status s '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Types ct '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '         ON a.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Credit_Terms e '
    SET @sql = @sql + '         ON a.Slu_AW_Credit_Terms_ID = e.Slu_AW_Credit_Terms_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AC_Account_Types f '
    SET @sql = @sql + '         ON a.Sys_AC_Account_Types_ID = f.Sys_AC_Account_Types_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Customer_Groups g '
    SET @sql = @sql + '         ON a.Lup_AC_Customer_Groups_ID = g.Lup_AC_Customer_Groups_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       a.Slu_AW_Active_ID = 1 '


    IF @Filter3 <> ''
        BEGIN
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter3 + '%'') OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter2 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter3 + '%'')) '

        END

    ELSE
	IF @Filter2 <> ''
		BEGIN 
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Surname like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Firstnames like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Cell_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Work_Tel_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         a.Home_Tel_No like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         b.Comment like ''%' + @Filter2 + '%'') OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + '%'' AND '
            SET @sql = @sql + '         c.Comment like ''%' + @Filter2 + '%'')) '
        END

    ELSE
	IF @Filter1 <> ''
        BEGIN
            SET @sql = @sql + '   AND ((a.Surname like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Firstnames like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Cell_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Work_Tel_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (a.Home_Tel_No like ''%' + @Filter1 + '%'' ) OR '
            SET @sql = @sql + '        (b.Comment like ''%' + @Filter1 + + '%'' ) OR '
            SET @sql = @sql + '        (c.Comment like ''%' + @Filter1 + + '%'' )) '
        END
--RGL 6.0 Added FirstNames to order by
    SET @sql = @sql + '   ORDER BY [Name], [FirstNames] '

EXEC (@sql)

SET NOCOUNT OFF
GO

--9 sp_AS_POS_RPT_Invoice_Print
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
-------------------------------------------------------------------------------
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(50),
 			@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
            
    --> 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
		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    
    --------------------------------------------------------------------

	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 '

	--SET @sql = @sql + ' RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') AS [CustomerName], '	
    --SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
    --SET @sql = @sql + ' THEN RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') + '' / '' + IsNull(c.Firstnames,'''')'
    --SET @sql = @sql + ' ELSE RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') '
    --SET @sql = @sql + ' END AS [CustomerName], '

	IF @AW_YesNo_Invoice = 1
	BEGIN
      SET @sql = @sql + '''' + @Customer_Name + '''' + ' AS [CustomerName], '	  
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
		SET @sql = @sql + ' THEN RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') + '' / '' + IsNull(c.Firstnames,'''')'
		SET @sql = @sql + ' ELSE RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') '
		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 + ' 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], '
    
    
    SET @sql = @sql + ' td.Quantity AS [DetailQty], '
    SET @sql = @sql + ' td.Unit_Price AS [DetailUnitPrice], '

    SET @sql = @sql + ' CASE WHEN (td.Unit_Price * td.Quantity) <> 0 '
    SET @sql = @sql + ' THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * td.Quantity)) * 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.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], '
    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], '
	
	--> 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], '
    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], '
    SET @sql = @sql + ' td.TDHeader AS [TDHeader], '
    SET @sql = @sql + ' td.TDDetail AS [TDDetail] '

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

--10 sp_RPT_AB_Income_Statement
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Income_Statement
--Purpose       :GAAP Income Statement Report
--Parameters    :
--Date          :2002/12/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :19/03/03 - Added ORDER BY AB_Accounts.Description to display
--              :           all report category accounts
--              :03/08/03 - Added Cost Center filtering
--              :14/04/05 - Added @IgnoreYEJnl input parameter that now displays
--              :           monthly account totals reflecting ACTUAL movement
--2004.2.7      :06/04/06 - Added @IgnoreZeroTrans and @IgnoreZeroBalance options
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.0	:2013-12-09 - Exclude year end GL's on balance and transaction checks
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AB_Income_Statement]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

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


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @CurrentMonthID OUTPUT,
                        @CurrentYearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth2ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear2ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior2], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth1ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear1ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior1], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @CurrentMonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @CurrentYearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    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


    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END



    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
		    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            SET @sql = @sql + '         ) '
		    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
            SET @sql = @sql + ' ) <> 0 '

        END



    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, '
--------------------------------------------------------------
--19/03/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------
--Select @EndPeriod

EXEC (@sql)


SET NOCOUNT OFF
GO

--11 sp_RPT_AC_Customer_Performance_Stats
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Customer_Performance_Stats]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Customer_Performance_Stats]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Performance_Statistics
--Purpose       :Retrieves Customers Performance Statistics
--              :
--Parameters    :
--Date          :2004/07/14
--Authors       :TB
--Version       :1.0.0
--MODS          :14/07/04 - Modified Options 4 & 6
--              :09/08/04 - Added Options 10 to 14
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Performance_Stats]
    (
        @Option tinyint,
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime
    )

AS

SET NOCOUNT ON

    DECLARE @Midnight		datetime,
			@OverdueCount	int

    SET @Midnight = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @ReportDate), 0, 1)))


    IF @Option = 1    --Customer Debtors Total, Overdue, Overdue %
        BEGIN
        
			SET @OverdueCount = 0
    		SELECT @OverdueCount = COUNT(Distinct a.AC_Customers_ID)
        	FROM AC_Customers a
        	INNER JOIN AS_Transactions t
        			ON a.AC_Customers_ID = t.AC_Customers_ID
        	LEFT JOIN Slu_AW_Credit_Terms b
                    ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
--        	WHERE AC_Customers_ID = @CustomerID AND
            WHERE (Sys_AW_Transaction_Types_ID = 3 OR       --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR        --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR        --Journal
                  Sys_AW_Transaction_Types_ID = 15 OR       --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18) AND     --EFT Payment
                  ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                --> If Transaction OLDER THAN @DaysTerms
                  DATEDIFF(d, @Midnight, Transaction_Date + b.Terms_Value) < 0
              
          	SELECT
--                COUNT(*) AS [OverdueCount],
				@OverdueCount AS [OverdueCount],
                SUM(ISNULL(dbo.fn_AC_Customer_Balance_As_At_Date
                            ( a.AC_Customers_ID,
                              @ReportDate), 0)) AS [Balance],
                SUM(ISNULL(dbo.fn_AC_Customer_Overdue_Amount
                            (a.Sys_AC_Credit_Term_Types_ID,
                             b.Terms_Value,
                             a.AC_Customers_ID,
                             @Midnight,
                             @D1,
                             @D2,
                             @D3,
                             @D4,
                             @D5,
                             @D6,
                             @D7), 0)) AS [Overdue]

        	FROM AC_Customers a
                LEFT JOIN Slu_AW_Credit_Terms b
                    ON b.Slu_AW_Credit_Terms_ID = a.Slu_AW_Credit_Terms_ID
        	WHERE a.AW_User_Companies_ID = @CompanyID
        END

    ELSE
    IF @Option = 2    --Total Value of SALES
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Sales]
            SELECT ISNULL(SUM(Total_Amount), 0) AS [Sales]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 -- ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END

    ELSE
    IF @Option = 3    --Total Value of REFUNDS (Credit Notes)
        BEGIN

            SELECT COUNT(*) AS [Count],
                   --RL 2014-09-02 ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Refunds]
                   ISNULL(SUM(Total_Amount), 0) AS [Refunds]                   
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 --RL 2014-09-02 ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                  Sys_AW_Transaction_Types_ID = 4      --Refund

        END

    ELSE
    IF @Option = 4    --Total Value of PAYMENTS RECEIVED
        BEGIN

            SELECT ISNULL(SUM(Total_Amount), 0) AS [Payments]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

        END

    ELSE
    IF @Option = 5    --Number of NEW ACCOUNTS OPENED
        BEGIN

			--Start_Date must be captured on Customer Catalog
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Start_Date >= @StartDate AND
                  Start_Date <= @EndDate

        END

    ELSE
    IF @Option = 6    --Total Debtors MOVEMENT for the period
        BEGIN

            SELECT ISNULL(SUM(Total_Amount), 0) AS [Total]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4 OR   --Refund
                  Sys_AW_Transaction_Types_ID = 5 OR   --Journal
                  Sys_AW_Transaction_Types_ID = 7 OR   --Payment
                  Sys_AW_Transaction_Types_ID = 15 OR  --Interest Journal
                  Sys_AW_Transaction_Types_ID = 18 OR  --Settlement Discount
                  Sys_AW_Transaction_Types_ID = 21 OR  --Back Office Payment
                  Sys_AW_Transaction_Types_ID = 22)    --EFT Payment

        END

    ELSE
    IF @Option = 7    --TOTAL SALES for last 3 months
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [SalesQtr]
            SELECT ISNULL(SUM(Total_Amount), 0) AS [SalesQtr]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                  --ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= DATEADD(m, -3, @ReportDate) AND
                  Transaction_Date <= @ReportDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END


    ELSE
    IF @Option = 8    --Customer Applications DECLINED this month
        BEGIN

            SELECT COUNT(*) AS [DeclinedCount]
            FROM AC_History_Status
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Sys_AC_Account_Status_ID = 5 AND        --5 = Declined
                  Date_Changed >= @StartDate AND
                  Date_Changed <= @EndDate

        END


    ELSE
    IF @Option = 9    --Total Value of SALES grouped by Terms Of Sale
        BEGIN
            SELECT MAX(a.AW_User_Companies_ID) AS [CompanyID],
                   MAX(c.Description) AS [TermsOfSale],
                   --RL 2014-09-02 ISNULL(SUM(a.Total_Amount), 0) + ISNULL(SUM(a.Payment_Amount), 0) AS [Sales]
                   ISNULL(SUM(a.Total_Amount), 0) AS [Sales]
            FROM AS_Transactions a
                LEFT JOIN AC_Customers b
                    ON b.AC_Customers_ID = a.AC_Customers_ID
                LEFT JOIN Sys_AC_Credit_Term_Types c
                    ON c.Sys_AC_Credit_Term_Types_ID = b.Sys_AC_Credit_Term_Types_ID
            WHERE a.AW_User_Companies_ID = @CompanyID AND
             --     ISNULL(a.Total_Amount, 0) + ISNULL(a.Payment_Amount, 0) <> 0 AND
                  a.Transaction_Date >= @StartDate AND
                  a.Transaction_Date <= @EndDate AND
                 (a.Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  a.Sys_AW_Transaction_Types_ID = 4)     --Refund
            GROUP BY b.Sys_AC_Credit_Term_Types_ID
            ORDER BY [TermsOfSale]

        END

--------------------------------------------------------

    ELSE
    IF @Option = 10    --Total Customers
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers

        END


    ELSE
    IF @Option = 11    --Total Active Customers
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE Slu_AW_Active_ID = 1

        END


    ELSE
    IF @Option = 12    --Customers with a Credit Limit
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers
            WHERE Credit_Limit > 0

        END


    ELSE
    IF @Option = 13    --Max Credit exposure
        BEGIN
            
            SELECT SUM(Credit_Limit) AS [Credit]
            FROM AC_Customers
            WHERE Credit_Limit > 0

        END


    ELSE
    IF @Option = 14    --Customers with a Credit Terms
        BEGIN
            
            SELECT COUNT(*) AS [Count]
            FROM AC_Customers a
                INNER JOIN Slu_AW_Credit_Terms b
                    ON a.Slu_AW_Credit_Terms_ID = b.Slu_AW_Credit_Terms_ID
            WHERE b.Terms_Value > 0

        END
    Else    
    IF @Option = 15    --Total Value of VAT on SALES
        BEGIN

            --RL 2014-09-02 SELECT ISNULL(SUM(Total_Amount), 0) + ISNULL(SUM(Payment_Amount), 0) AS [Sales]
            SELECT ISNULL(SUM(Total_Tax_Amount), 0) AS [VAT]
            FROM AS_Transactions
            WHERE AW_User_Companies_ID = @CompanyID AND
                 -- ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                  Transaction_Date >= @StartDate AND
                  Transaction_Date <= @EndDate AND
                 (Sys_AW_Transaction_Types_ID = 3 OR   --Invoice
                  Sys_AW_Transaction_Types_ID = 4)     --Refund

        END




SET NOCOUNT OFF
GO

--12 sp_RPT_AS_Sales_Transaction_Listing
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_Sales_Transaction_Listing]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_Sales_Transaction_Listing]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Transaction_Listing
--Purpose       :Sales Transaction Listing
--Date          :2010/08/07
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Transaction_Listing]
    (
        @CompanyID int,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
	    @Option tinyint,
	    @Filter tinyint,
        @Sort tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

    IF @Filter = 0
        SET @sql = @sql + ' o.AW_Users_ID AS [HeaderID], ' +
                          ' o.[Surname] + ISNULL('', '' + o.FirstName, '''') AS [Filter], '
    ELSE
    IF @Filter = 1
        SET @sql = @sql + ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
                          ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 2
        SET @sql = @sql + ' ISNULL(o.Lup_AS_Reps_ID,0) AS [HeaderID], ' +
                          ' ISNULL(o.[Description],''<None>'') AS [Filter], '
    ELSE
    IF @Filter = 3
        SET @sql = @sql + ' ISNULL(o.Lup_AS_Reps_ID,0) AS [HeaderID], ' +
                          ' ISNULL(o.[Description],''<None>'') AS [Filter], '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' t.AC_Customers_ID AS [CustID], '
    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 + ' t.Date_Captured AS [Captured], '
    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [TranType], '
    SET @sql = @sql + ' t.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 + ' RTRIM(LTRIM(ISNULL('' '' + u.UserName, ''''))) AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = t.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_Users u '
    SET @sql = @sql + '          ON t.User_ID = u.AW_Users_ID '

    IF @Filter = 0
        SET @sql = @sql + '    LEFT JOIN AW_Users o ' +
                          '        ON t.User_ID = o.AW_Users_ID '
    ELSE
    IF @Filter = 1
        SET @sql = @sql + '    LEFT JOIN Lup_AC_Sales_Areas o ' +
                          '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 2
        SET @sql = @sql + '    LEFT JOIN Lup_AS_Reps o ' +
                          '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    ELSE
    IF @Filter = 3
        SET @sql = @sql + '    LEFT JOIN Lup_AS_Reps o ' +
                          '        ON t.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND t.Day_End >= ' + '''' + CONVERT(varchar(30), @DayEndFromDate) + '''' + ' '
    SET @sql = @sql + '  AND t.Day_End <= ' + '''' + CONVERT(varchar(30), @DayEndToDate) + '''' + ' '


    IF @Option = 0
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 1 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 2 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 3 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 4 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 5 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 15 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 16 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 18 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 23) '
        END

    ELSE
    IF @Option = 1
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 1 '
        END
    ELSE
    IF @Option = 2
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 2 '
        END
    ELSE
    IF @Option = 3
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 3 '
        END
    ELSE
    IF @Option = 4
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 4 '
        END
    ELSE
    IF @Option = 5
        BEGIN
            SET @sql = @sql + '  AND (t.Sys_AW_Transaction_Types_ID = 7 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 21 '
            SET @sql = @sql + '    OR t.Sys_AW_Transaction_Types_ID = 22) '
        END
    ELSE
    IF @Option = 6
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 5 '
        END
    ELSE
    IF @Option = 7
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 15 '
        END
    ELSE
    IF @Option = 8
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 18 '
        END
    ELSE
    IF @Option = 9
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 16 '
        END
    ELSE
    IF @Option = 10
        BEGIN
            SET @sql = @sql + '  AND t.Sys_AW_Transaction_Types_ID = 23 '
        END


    IF @Sort = 0        --Date Captured
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Captured] ASC '
        END
    ELSE
    IF @Sort = 1        --Transaction Date
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [TranDate] ASC '
        END
    ELSE
    IF @Sort = 2        --Transaction Number
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [TranNo] ASC '
        END
    ELSE
    IF @Sort = 3        --Customer
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Customer] ASC '
        END


    EXEC (@sql)

SET NOCOUNT OFF
GO

--13 sp_AP_Update_Product_Prices
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_Prices]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_Prices]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Prices
--Purpose       :UPDATE Price Update Products in CURSOR using Product Code & Size
--Date          :2006/06/13
--Authors       :TB
--MODS:         :
--2004.4.0      :19/07/08 - Added validation if Price Update for this Product
--              :           HAS NOT ALREADY BEEN LOADED. If NO then LOAD update
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Prices]
	(
        @ProductCode varchar(20),
        @EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ChkReplaceCost int,
        @ChkActiveOnly int,
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ProductID int,
            @Price1EffectiveDate datetime,
            @Price1Price1 money,
            @Price1Price2 money,
            @Price2EffectiveDate datetime,
            @Price2Price1 money,
            @Price2Price2 money,
            @AllreadyLoaded tinyint


    SET @AllreadyLoaded = 0


    IF @ChkActiveOnly = 1        --Update only ACTIVE Products that match Product Code
        BEGIN
        	DECLARE Product_Cursor CURSOR FOR
                (
                    SELECT AP_Products_ID,
                           Price1_Effective_Date,
                           Price1_Price1,
                           Price1_Price2,
                           Price2_Effective_Date,
                           Price2_Price1,
                           Price2_Price2
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode
                      AND AW_User_Companies_ID = @CompanyID
                      AND Slu_AW_Active_ID = 1
                )
        END
    ELSE                         --Update ALL Products that match Product Code
        BEGIN
        	DECLARE Product_Cursor CURSOR FOR
                (
                    SELECT AP_Products_ID,
                           Price1_Effective_Date,
                           Price1_Price1,
                           Price1_Price2,
                           Price2_Effective_Date,
                           Price2_Price1,
                           Price2_Price2
                    FROM AP_Products
                    WHERE Product_Code = @ProductCode
                      AND AW_User_Companies_ID = @CompanyID
                )
        END



	OPEN Product_Cursor

    	FETCH NEXT FROM Product_Cursor 
    	INTO
            @ProductID,
            @Price1EffectiveDate,
            @Price1Price1,
            @Price1Price2,
        	@Price2EffectiveDate,
            @Price2Price1,
            @Price2Price2


    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            SET @AllreadyLoaded = 0


            --> Validate if ALREADY LOADED
            IF @Price1EffectiveDate IS NOT NULL
                BEGIN
                    IF @Price1EffectiveDate = @EffectiveDate AND @Price1Price1 = @Price1
                        BEGIN
                            SET @AllreadyLoaded = 1
                        END
                END

            IF @Price2EffectiveDate IS NOT NULL
                BEGIN
                    IF @Price2EffectiveDate = @EffectiveDate AND @Price2Price1 = @Price1
                        BEGIN
                            SET @AllreadyLoaded = 1
                        END
                END


            IF @AllreadyLoaded = 0
                BEGIN
                    --> If Price1 is OLDEST price
                    --IF @Price1EffectiveDate <= @Price2EffectiveDate
                    --RL 2014-10-15 Added ISNULL check. Need to test
					IF @Price1EffectiveDate <= ISNULL(@Price2EffectiveDate,'1900-01-01')                    
                        BEGIN
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> If Price2 is OLDEST price
                    ELSE
                    IF ISNULL(@Price2EffectiveDate,'1900-01-01') <= @Price1EffectiveDate
                        BEGIN
                            --> Move Price1 to Price2
                        	UPDATE AP_Products
                            SET Price2_Effective_Date = @Price1EffectiveDate,
                                Price2_Price1 = @Price1Price1,
                                Price2_Price2 = @Price1Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                
                            --> Put NEW prices into Price1
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> If Price1 = Price2 and both dates are probably NULL
                    ELSE
                        BEGIN
                            --> Put NEW prices into Price1
                        	UPDATE AP_Products
                            SET Price1_Effective_Date = @EffectiveDate,
                                Price1_Price1 = @Price1,
                                Price1_Price2 = @Price2,
                                [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END

                    --> Replace Last Cost with the Cost in list
                    IF @ChkReplaceCost = 1
                        BEGIN
                        	UPDATE AP_Products
                            SET Last_Cost = @LastCost,
                            [User_ID] = @UserID
                            WHERE AP_Products_ID = @ProductID
                        END
                END


        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @Price1EffectiveDate,
                @Price1Price1,
                @Price1Price2,
            	@Price2EffectiveDate,
                @Price2Price1,
                @Price2Price2

        END
    	
	CLOSE Product_Cursor

	DEALLOCATE Product_Cursor
GO

--14 alt_AP_Products Slu_AW_YesNo_Sell_Below_Cost
--Sell product below cost on product level
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='AP_Products' AND
        C.Name='Slu_AW_YesNo_Sell_Below_Cost'
) 
ALTER TABLE AP_Products ADD Slu_AW_YesNo_Sell_Below_Cost tinyint NULL
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Sell_Below_Cost]'
-------------------------------------------------------
GO
UPDATE AP_Products
SET Slu_AW_YesNo_Sell_Below_Cost = 0
WHERE Slu_AW_YesNo_Sell_Below_Cost IS NULL	
GO
UPDATE AP_Products
SET Levy_Weight_ID = 0
WHERE Levy_Weight_ID IS NULL	
GO
UPDATE AP_Products
SET Product_Weight = 0.00
WHERE Product_Weight IS NULL	
GO
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Product_Weight]'
-------------------------------------------------------
GO

--15 sp_AP_Select_Product_Catalog
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
---------------------------------------------------------------------------------
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(9, 3), dbo.fn_AP_Products_Job_Reserved(AP_Products_ID)) as [Job Reserved], 
    	--Quote_Reserved AS [Quote Reserved],
    	CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(AP_Products_ID)) as [Quote Reserved], 
    	--Sales_Order_Reserved AS [Sales Order Reserved],
    	CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(AP_Products_ID)) as [Sales Order Reserved], 
    	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(9, 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

--16 Moved to bottom of script
--17 vw_AS_POS_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AS_POS_Products]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AS_POS_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Products    -- now REDUNDANT
--Purpose       :Extracts POS NORMAL Lookup Products 
--Date          :2002/02/16
--Functionality :Tables: AP_Products + 10 LUP Joins
--Authors       :TB
--Version       :1.0.0
--MODS          :26/07/02 - Converted [Gross Margin] from FLOAT to MONEY
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :02/06/03 - Added Average Margin field based on Average_Cost
--              :03/07/03 - Changed Discount GroupID field
--              :           from  p.Lup_AP_Product_Groups_ID as [GroupID]
--              :           to    p.Lup_AP_Discount_Groups_ID as [GroupID]
--              :20/12/03 - Added MinGPPerc field based on Min_GP_Percentage
--              :12/01/04 - Added [Edit Discount] alias to Slu_AW_YesNo_Edit_Price
--              :19/01/04 - Added ISNULL validation of NULL Product_Code
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :           Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :26/02/04 - Added [PromoPrice] from fn_AP_Get_Sales_Promotion_Price
--              :28/02/04 - Added [GrossProfit] to fix POS MARGIN sorts (+ & -)
--              :28/02/04 - Added [PromoProductID] from fn_AP_Get_Sales_Promotion_Product_ID
--2004.2.7      :12/04/06 - Removed Quote_Reserved from [Qty Reserved]
--2004.3.4      :30/12/06 - Reworked Job Card and Sales Order Reserved in realtime
--              :           using fn_AP_SUM_Product_Job_Reserved
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS
--              :           2. Moving this code to sp_AS_POS_Products_Select
--Now Retired   :           Now Retired
--              :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
--              :13/08/07 - Removed unused [OpenOrderQty] 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.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--RL	V5.6	:2014-04-10 - Added Sell Below Cost
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [dbo].[vw_AS_POS_Products]
AS

	SELECT 
		p.Description, 
		ISNULL(p.Product_Code, '') as [Code], 
		p.Last_Cost AS [Last Cost], 
		0 as [Standard Discount],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, 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(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2, getdate()) as [Price 2],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as [Unit Price],
		p.Pack_Size AS [Qty],
		0 as [Discount %],
		0 as [Discount],
--		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) as Price,
		p.AP_Products_ID as [ID],
		p.Lup_AP_Product_Types_ID as [TypeID],
--		tc.Description AS [Tax Code], 
		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, 
        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.Date_Captured AS [Date], 
--		p.User_ID AS [UserID], 
        p.AW_User_Companies_ID AS [CompanyID],
        p.Slu_AW_Active_ID AS [Active],
        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
        CONVERT(money, dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, 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(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, 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.SKU_Code AS [SKU_Code],
        p.Supercession AS [Supercession],
        p.Alternate_Code1 AS [Alternate_Code1],
        p.Alternate_Code2 AS [Alternate_Code2],
        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost]        
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
GO

--18 vw_AS_POS_Products_Gross_Contribution
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AS_POS_Products_Gross_Contribution]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AS_POS_Products_Gross_Contribution]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :vw_AS_POS_Products_Gross_Contribution
--Purpose       :Extracts POS NORMAL Lookup Products 
--Date          :2002/02/16
--Functionality :Tables: AP_Products + 10 LUP Joins
--Authors       :TB
--MODS          :26/07/02 - Converted [Gross Margin] from FLOAT to MONEY
--              :04/02/03 - Added 'Active' to filter out inactive products in POS
--              :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :02/06/03 - Added Average Margin field based on Average_Cost
--              :03/07/03 - Changed Discount GroupID field
--              :           from  p.Lup_AP_Product_Groups_ID as [GroupID]
--              :           to    p.Lup_AP_Discount_Groups_ID as [GroupID]
--              :20/12/03 - Added MinGPPerc field based on Min_GP_Percentage
--              :12/01/04 - Added [Edit Discount] alias to Slu_AW_YesNo_Edit_Price
--              :19/01/04 - Added ISNULL validation of NULL Product_Code
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :           Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :26/02/04 - Added [Promotion] from fn_AP_Get_Sales_Promotion_Price
--              :28/02/04 - Added [GrossProfit] to fix POS MARGIN sorts (+ & -)
--              :28/02/04 - Added [PromoProductID] from fn_AP_Get_Sales_Promotion_Product_ID
--2004.2.7      :12/04/06 - Removed Quote_Reserved from [Qty Reserved]
--2004.3.4      :30/12/06 - Reworked Job Card and Sales Order Reserved in realtime
--              :           using fn_AP_SUM_Product_Job_Reserved
--2004.3.7      :26/07/07 - Reworked to improve performance:
--              :           1. Stripped off unused FIELDS and JOINS
--              :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
--              :13/08/07 - Removed unused [OpenOrderQty] 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.5.0      :12/03/11 - Added to search in SKU_Code, Supercession,Alternate_Code1, Alternate_Code1 code - Andre Roux
--RL	V5.6	:2014-04-10 - Added Sell Below Cost
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [dbo].[vw_AS_POS_Products_Gross_Contribution]
AS

	SELECT 
		p.Description, 
		ISNULL(p.Product_Code, '') as [Code],
		p.Last_Cost AS [Last Cost], 
		0 as [Standard Discount],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, 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.GetGrossContribution(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) as [Price 2],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, 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, 
        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(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, 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(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, 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.SKU_Code AS [SKU_Code],
        p.Supercession AS [Supercession],
        p.Alternate_Code1 AS [Alternate_Code1],
        p.Alternate_Code2 AS [Alternate_Code2],
        p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
GO

--19_sp_AS_Shape_Transaction_Search_Header
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_Search_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header
--Purpose       :Selects POS Transaction Header Shaped for Document Reprint
--Date          :2003/12/18
--Authors       :TB
--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 clause IF @CustomerID <> 0
--              :06/12/04 - Added CASE statement to not calculate GP on PAYMENTS
--2004.3.7      :11/07/07 - Added AW_Comments as [Notes]
--2004.4.0      :11/07/08 - Added Sales Order transaction type = 16
--2004.4.2      :26/10/08 - Replaced [Ref No] (Transaction_Number) field with [No] and
--              :           added [Ref No] (Customer_Reference) field
--2004.4.7      :13/09/09 - Added new Stock Transfer transaction type = 23
--2004.5.8      :2013-02-20 - Added search for AS_Job_References_ID and Serial_No
--V6.0	RL	2014-09-09	: - Added new Select Proforma TranType = 13 where required
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header]
	(
        @CustomerID int,
        @SearchString varchar(50),
        @Filter1 varchar(50) = NULL,
        @Filter2 varchar(50) = NULL,
        @Filter3 varchar(50) = NULL,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

-------------------------------------------------------------------------------
    IF @CustomerID <> 0
        BEGIN
        --> 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.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                        tt.[Description] AS [Type],
                        t.Transaction_Date AS [Date],
                        t.Transaction_Number AS [No],
                        t.Customer_Reference 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.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],
                        com.Comment AS [Notes],
                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                        act.[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 act
                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                        LEFT JOIN AW_Comments com
                            ON t.AW_Comments_ID = com.AW_Comments_ID
                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                          t.AC_Customers_ID = @CustomerID 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.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],

                        tt.[Description] AS [Type],
                        t.Transaction_Date AS [Date],
                        t.Transaction_Number AS [No],
                        t.Customer_Reference 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.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],
                        com.Comment AS [Notes],
                        ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                        act.[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 act
                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                        LEFT JOIN AW_Comments com
                            ON t.AW_Comments_ID = com.AW_Comments_ID
                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                          t.AC_Customers_ID = @CustomerID 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 = 13 or 
                           t.Sys_AW_Transaction_Types_ID = 15 or 
                           t.Sys_AW_Transaction_Types_ID = 16 or 
                    	   t.Sys_AW_Transaction_Types_ID = 18 or
                           t.Sys_AW_Transaction_Types_ID = 21 or 
                           t.Sys_AW_Transaction_Types_ID = 22 or 
                    	   t.Sys_AW_Transaction_Types_ID = 23) AND
                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                    ORDER BY t.Transaction_Date DESC
                END
        END
-------------------------------------------------------------------------------
    ELSE    --(IF @CustomerID = 0)
        BEGIN
        --> Specific Transaction Type
            IF @TransactionTypeID <> 0
                BEGIN
----------------------------------------->>>>>>>
                    IF @SearchString <> ''
                        BEGIN
----------------------------------------->>>>>>>
                			IF @Filter3 <> ''
                				BEGIN
                					SET @Filter3 = '%' +  @Filter3 + '%'
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                         ((c.Surname like @Filter1 AND
                                           c.Surname like @Filter2 AND
                                           c.Surname like @Filter3 ) OR 
                                          (c.Firstnames like @Filter1 AND
                                           c.Firstnames like @Filter2 AND
                                           c.Firstnames like @Filter3) OR 
                                          (c.Cell_No like @Filter1 AND
                                           c.Cell_No like @Filter2 AND
                                           c.Cell_No like @Filter3) OR 
                                          (c.Work_Tel_No like @Filter1 AND
                                           c.Work_Tel_No like @Filter2 AND
                                           c.Work_Tel_No like @Filter3) OR 
                                          (c.Home_Tel_No like @Filter1 AND
                                           c.Home_Tel_No like @Filter2 AND
                                           c.Home_Tel_No like @Filter3) OR 
                                          (t.Transaction_Number like @Filter1 AND
                                           t.Transaction_Number like @Filter2 AND
                                           t.Transaction_Number like @Filter3) OR
                                          (t.Customer_Reference like @Filter1 AND
                                           t.Customer_Reference like @Filter2 AND
                                           t.Customer_Reference like @Filter3) OR
                                          (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter2 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter3) OR
                                          (t.Comment like @Filter1 AND
                                           t.Comment like @Filter2 AND
                                           t.Comment like @Filter3) OR
                                          (com.Comment like @Filter1 AND
                                           com.Comment like @Filter2 AND
                                           com.Comment like @Filter3) OR
--2004.5.8                                          
                                          (d.AS_Job_References_ID like @Filter1 AND
                                           d.AS_Job_References_ID like @Filter2 AND
                                           d.AS_Job_References_ID like @Filter3) OR                                        
                                          (d.Serial_No like @Filter1 AND
                                           d.Serial_No like @Filter2 AND
                                           d.Serial_No like @Filter3) OR
--2004.5.8                                                                                                                               
                                          (a.Reg_No like @Filter1 AND
                                           a.Reg_No like @Filter2 AND
                                           a.Reg_No like @Filter3)) 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 = 13 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 or 
                    	                   t.Sys_AW_Transaction_Types_ID = 23) AND
                                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter2 <> ''
                				BEGIN
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                        ((c.Surname like @Filter1 AND
                                          c.Surname like @Filter2) OR
                                         (c.Firstnames like @Filter1 AND
                                          c.Firstnames like @Filter2) OR
                                         (c.Cell_No like @Filter1 AND
                                          c.Cell_No like @Filter2) OR
                                         (c.Work_Tel_No like @Filter1 AND
                                          c.Work_Tel_No like @Filter2) OR
                                         (c.Home_Tel_No like @Filter1 AND
                                          c.Home_Tel_No like @Filter2) OR
                                         (t.Transaction_Number like @Filter1 AND
                                          t.Transaction_Number like @Filter2) OR
                                         (t.Customer_Reference like @Filter1 AND
                                          t.Customer_Reference like @Filter2) OR
                                         (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter2) OR
                                         (t.Comment like @Filter1 AND
                                          t.Comment like @Filter2) OR
                                         (com.Comment like @Filter1 AND
                                          com.Comment like @Filter2) OR
--2004.5.8                                          
                                          (d.AS_Job_References_ID like @Filter1 AND
                                           d.AS_Job_References_ID like @Filter2) OR                                        
                                          (d.Serial_No like @Filter1 AND
                                           d.Serial_No like @Filter2) OR
--2004.5.8                                                                                    
                                         (a.Reg_No like @Filter1 AND
                                          a.Reg_No like @Filter2)) 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 = 13 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 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 23) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter1 <> ''
                				BEGIN
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
                                          t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
        
                                         (c.Surname like @Filter1 OR
                                          c.Firstnames like @Filter1 OR
                                          c.Cell_No like @Filter1 OR
                                          c.Work_Tel_No like @Filter1 OR
                                          c.Home_Tel_No like @Filter1 OR
                                          t.Transaction_Number like @Filter1 OR
                                          t.Customer_Reference like @Filter1 OR
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter1 OR
                                          t.Comment like @Filter1 OR
                                          com.Comment like @Filter1 OR
--2004.5.8                                          
                                          d.AS_Job_References_ID like @Filter1 OR                                        
                                          d.Serial_No like @Filter1 OR
--2004.5.8                                          
                                          a.Reg_No like @Filter1) 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 = 13 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 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 23) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
                        END
----------------------------------------->>>>>>>
                    ELSE
                        BEGIN
                            SELECT DISTINCT
                                t.AS_Transactions_ID AS [ID],
                                t.AC_Customers_ID AS [CustomerID],
                                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                tt.[Description] AS [Type],
                                t.Transaction_Date AS [Date],
                                t.Transaction_Number AS [No],
                                t.Customer_Reference 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.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],
                                act.[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 act
                                    ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                            WHERE 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
----------------------------------------->>>>>>>
                END
-----------------------------------------
        --> ALL Transaction Types
            ELSE
                BEGIN
----------------------------------------->>>>>>>
                    IF @SearchString <> ''
                        BEGIN
----------------------------------------->>>>>>>
                			IF @Filter3 <> ''
                				BEGIN
                					SET @Filter3 = '%' +  @Filter3 + '%'
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                         ((c.Surname like @Filter1 AND
                                           c.Surname like @Filter2 AND
                                           c.Surname like @Filter3 ) OR 
                                          (c.Firstnames like @Filter1 AND
                                           c.Firstnames like @Filter2 AND
                                           c.Firstnames like @Filter3) OR 
                                          (c.Cell_No like @Filter1 AND
                                           c.Cell_No like @Filter2 AND
                                           c.Cell_No like @Filter3) OR 
                                          (c.Work_Tel_No like @Filter1 AND
                                           c.Work_Tel_No like @Filter2 AND
                                           c.Work_Tel_No like @Filter3) OR 
                                          (c.Home_Tel_No like @Filter1 AND
                                           c.Home_Tel_No like @Filter2 AND
                                           c.Home_Tel_No like @Filter3) OR 
                                          (t.Transaction_Number like @Filter1 AND
                                           t.Transaction_Number like @Filter2 AND
                                           t.Transaction_Number like @Filter3) OR
                                          (t.Customer_Reference like @Filter1 AND
                                           t.Customer_Reference like @Filter2 AND
                                           t.Customer_Reference like @Filter3) OR
                                          (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter2 AND
                                           CONVERT(varchar(30), t.Total_Amount) like @Filter3) OR
                                          (t.Comment like @Filter1 AND
                                           t.Comment like @Filter2 AND
                                           t.Comment like @Filter3) OR
                                          (com.Comment like @Filter1 AND
                                           com.Comment like @Filter2 AND
                                           com.Comment like @Filter3) OR
--2004.5.8                                          
                                         (d.AS_Job_References_ID like @Filter1 AND
                                          d.AS_Job_References_ID like @Filter2 AND
                                          d.AS_Job_References_ID like @Filter3) OR
                                         (d.Serial_No like @Filter1 AND
                                          d.Serial_No like @Filter2 AND
                                          d.Serial_No like @Filter3) OR                                          
--2004.5.8                                                                                     
                                          (a.Reg_No like @Filter1 AND
                                           a.Reg_No like @Filter2 AND
                                           a.Reg_No like @Filter3)) 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 = 13 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 or 
                    	                   t.Sys_AW_Transaction_Types_ID = 23) AND
                                           DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                           DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter2 <> ''
                				BEGIN
                					SET @Filter2 = '%' +  @Filter2 + '%'
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                        ((c.Surname like @Filter1 AND
                                          c.Surname like @Filter2) OR
                                         (c.Firstnames like @Filter1 AND
                                          c.Firstnames like @Filter2) OR
                                         (c.Cell_No like @Filter1 AND
                                          c.Cell_No like @Filter2) OR
                                         (c.Work_Tel_No like @Filter1 AND
                                          c.Work_Tel_No like @Filter2) OR
                                         (c.Home_Tel_No like @Filter1 AND
                                          c.Home_Tel_No like @Filter2) OR
                                         (t.Transaction_Number like @Filter1 AND
                                          t.Transaction_Number like @Filter2) OR
                                         (t.Customer_Reference like @Filter1 AND
                                          t.Customer_Reference like @Filter2) OR
                                         (CONVERT(varchar(30), t.Total_Amount) like @Filter1 AND
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter2) OR
                                         (t.Comment like @Filter1 AND
                                          t.Comment like @Filter2) OR
                                         (com.Comment like @Filter1 AND
                                          com.Comment like @Filter2) OR
--2004.5.8                                          
                                         (d.AS_Job_References_ID like @Filter1 AND
                                          d.AS_Job_References_ID like @Filter2) OR
                                         (d.Serial_No like @Filter1 AND
                                          d.Serial_No like @Filter2) OR                                          
--2004.5.8                                          
                                         (a.Reg_No like @Filter1 AND
                                          a.Reg_No like @Filter2)) 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 = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 16 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 23) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
        
                			IF @Filter1 <> ''
                				BEGIN
                					SET @Filter1 = '%' +  @Filter1 + '%'
        
                                    SELECT DISTINCT
                                        t.AS_Transactions_ID AS [ID],
                                        t.AC_Customers_ID AS [CustomerID],
                                        RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                        tt.[Description] AS [Type],
                                        t.Transaction_Date AS [Date],
                                        t.Transaction_Number AS [No],
                                        t.Customer_Reference 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.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],
                                        act.[Description] AS [Active],
                                       	t.Sys_AW_Transaction_Types_ID AS [TypeID]
                                    FROM AS_Transactions t
--2004.5.8                                    
										LEFT OUTER JOIN AS_Transaction_Details d
											ON t.AS_Transactions_ID = d.AS_Transactions_ID
--2004.5.8											                                    
                                        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
                                        LEFT JOIN AC_Assets a
                                            ON c.AC_Customers_ID = a.AC_Customers_ID
                                        LEFT JOIN AW_Comments com
                                            ON t.AW_Comments_ID = com.AW_Comments_ID
                                        INNER JOIN AW_Users u
                                            ON t.[User_ID] = u.AW_Users_ID
                                        INNER JOIN Slu_AW_Active act
                                            ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                                    WHERE t.AW_User_Companies_ID = @CompanyID AND
        
                                         (c.Surname like @Filter1 OR
                                          c.Firstnames like @Filter1 OR
                                          c.Cell_No like @Filter1 OR
                                          c.Work_Tel_No like @Filter1 OR
                                          c.Home_Tel_No like @Filter1 OR
                                          t.Transaction_Number like @Filter1 OR
                                          t.Customer_Reference like @Filter1 OR
                                          CONVERT(varchar(30), t.Total_Amount) like @Filter1 OR
                                          t.Comment like @Filter1 OR
                                          com.Comment like @Filter1 OR
--2004.5.8                                          
                                          d.AS_Job_References_ID like @Filter1 OR
                                          d.Serial_No like @Filter1 OR                                          
--2004.5.8                                                                                    
                                          a.Reg_No like @Filter1) 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 = 13 or  
                                          t.Sys_AW_Transaction_Types_ID = 15 or 
                                          t.Sys_AW_Transaction_Types_ID = 16 or 
                                          t.Sys_AW_Transaction_Types_ID = 18 or
                                          t.Sys_AW_Transaction_Types_ID = 21 or 
                                          t.Sys_AW_Transaction_Types_ID = 22 or 
                    	                  t.Sys_AW_Transaction_Types_ID = 23) AND
                                          DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                          DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
                                    ORDER BY t.Transaction_Date DESC
                                END
                        END
----------------------------------------->>>>>>>
                    ELSE
                        BEGIN
                            SELECT DISTINCT
                                t.AS_Transactions_ID AS [ID],
                                t.AC_Customers_ID AS [CustomerID],
                                RTRIM(LTRIM(ISNULL(c.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                                tt.[Description] AS [Type],
                                t.Transaction_Date AS [Date],
                                t.Transaction_Number AS [No],
                                t.Customer_Reference 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.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],
                                act.[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 act
                                    ON t.Slu_AW_Active_ID = act.Slu_AW_Active_ID
                            WHERE (DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                                   DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
                            ORDER BY t.Transaction_Date DESC
                        END
----------------------------------------->>>>>>>
                END
        END
GO

--20 alt_AC_Contract_Prices_MinSaleQty
--Contract price for sale quantity limits
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='AC_Contract_Prices' AND
        C.Name='MinSaleQty'
) 
ALTER TABLE AC_Contract_Prices ADD MinSaleQty Decimal(9,3) NULL
GO    
       
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[MinSaleQty]'
-------------------------------------------------------
GO 
UPDATE AC_Contract_Prices
SET MinSaleQty = 0
WHERE MinSaleQty IS NULL	
GO

--21 sp_AP_Insert_Contract_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Insert_Contract_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Insert_Contract_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Contract_Products
--Purpose       :INSERT Customer Contract Prices
--Parameters    :
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Contract_Products]
	(
        @CustomerID int,
        @ProductID int,
        @Product varchar(50),
        @ProductCode varchar(20),
        @StartDate datetime,
        @EndDate datetime,
        @PackSize [decimal](9, 3),
        @UnitPrice money,
        @DiscountPerc decimal(9,3),
        @DiscountAmount money,
        @MinSaleQty decimal(9,3),
        @Active tinyint,
        @UserID int,
        @CompanyID int
	)
AS

SET NOCOUNT ON

    DECLARE @ContractProductID int

    INSERT AC_Contract_Prices
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Start_Date,
            End_Date,
            Pack_Size,
            Unit_Price,
            Discount_Perc,
            Discount_Amount,
            MinSaleQty,
            [User_ID],
            AW_User_Companies_ID,
            Slu_AW_Active_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Product,
            @ProductCode,
            @StartDate,
            @EndDate,
            @PackSize,
            @UnitPrice,
            @DiscountPerc,
            @DiscountAmount,
            @MinSaleQty,
            @UserID,
            @CompanyID,
            @Active
        )

	SELECT @ContractProductID = Scope_Identity() 

RETURN @ContractProductID

SET NOCOUNT OFF
GO

--22 sp_AP_Select_Customer_Contract_Prices
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Customer_Contract_Prices]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Customer_Contract_Prices]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Customer_Contract_Prices
--Purpose       :Select Customer Contract Price data
--Functionality :
--Date          :2004/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :12/03/04 - Added Product Description and Product Code to table and
--              :           Removed JOIN with AP_Products for rs updateability
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)
   
	SET @sql = ' SELECT '
    SET @sql = @sql + ' cp.AC_Contract_Prices_ID AS [ContractID], '
    SET @sql = @sql + ' cp.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' cp.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' cp.[Description] AS [Product], '
    SET @sql = @sql + ' cp.Product_Code AS [Code], '
    SET @sql = @sql + ' cp.Start_Date AS [Starts], '
    SET @sql = @sql + ' cp.End_Date AS [Ends], '
    SET @sql = @sql + ' cp.Pack_Size AS [Unit], '
    SET @sql = @sql + ' cp.Unit_Price AS [Unit Price], '
    SET @sql = @sql + ' cp.Discount_Perc AS [Discount %], '
    SET @sql = @sql + ' cp.Discount_Amount AS [Discount], '
    SET @sql = @sql + ' cp.MinSaleQty AS [Min Sale Qty], '    
    SET @sql = @sql + ' cp.Slu_AW_Active_ID AS [Status] '

    SET @sql = @sql + ' FROM AC_Contract_Prices cp '
    SET @sql = @sql + ' WHERE cp.AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + '   AND cp.AC_Customers_ID = ' + CONVERT(varchar(20), @CustomerID) + ' '
    SET @sql = @sql + ' ORDER BY cp.[Description] '

SET NOCOUNT OFF

EXEC (@sql)
GO

--23 sp_AP_Select_Export_Contract_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Export_Contract_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Export_Contract_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Export_Contract_Products
--Purpose       :Select Customer Contract Products to export
--Date          :2004/04/08
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	:MinSaleQty - Contract price if minimum quantity sold 
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

    SELECT
        AP_Products_ID AS [ProductID],
        ISNULL([Description], '') AS [Product],
        ISNULL(Product_Code, '') AS [Code],
        ISNULL(CONVERT(CHAR(10), Start_Date, 121), '') AS [Starts],
        ISNULL(CONVERT(CHAR(10), End_Date, 121), '') AS [Ends],
        ISNULL(Pack_Size, 1) AS [Unit],
        ISNULL(Unit_Price, 0) AS [Unit Price],
        ISNULL(Discount_Perc, 0) AS [Discount %],
        ISNULL(Discount_Amount, 0) AS [Discount],
        ISNULL(MinSaleQty, 0) AS [MinSaleQty]        
--        ISNULL(Slu_AW_Active_ID, 1) AS [Status]
    FROM AC_Contract_Prices
    WHERE AW_User_Companies_ID = @CompanyID AND
          AC_Customers_ID = @CustomerID
    ORDER BY ISNULL([Description], '')

SET NOCOUNT OFF
GO

--24 sp_AS_POS_Select_Contract_Prices
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Select_Contract_Prices]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Select_Contract_Prices]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_Contract_Prices
--Purpose       :Fetch product prices ON CONTRACT
--Date          :2004/03/13
--Authors       :TB
--Version       :1.0.0
--MODS          :03/06/04 - Added validation If Contract Product ACTIVE
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_Select_Contract_Prices]
    (
        @CustomerID int,
        @ProductID int,
        @Qty decimal(9,3),
        @UnitPrice money OUTPUT,
        @DiscPerc decimal(9, 3) OUTPUT,
        @DiscAmount money OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @Today datetime

    SET @Today = CONVERT(datetime, CONVERT(CHAR(10), getdate(), 121))

    SELECT TOP 1 @UnitPrice = ISNULL(Unit_Price, 0),
                 @DiscPerc = ISNULL(Discount_Perc, 0),
                 @DiscAmount = ISNULL(Discount_Amount, 0)
    FROM AC_Contract_Prices
    WHERE AC_Customers_ID = @CustomerID AND
          AP_Products_ID = @ProductID AND
         (@Today >= Start_Date AND            -- If PRODUCT still ACTIVE
          @Today <= End_Date) AND
          Slu_AW_Active_ID = 1 AND            -- If Contract Product ACTIVE
          MinSaleQty <= @Qty
    Order BY MinSaleQty DESC    

SET NOCOUNT OFF
GO

--25_1 tbl_Slu_AC_Documents
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[Slu_AC_Documents]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	CREATE TABLE [dbo].[Slu_AC_Documents]
	(
		[Slu_AC_Documents_ID] [tinyint] IDENTITY(1,1) NOT NULL,
		[Document_Layout] [varchar](50) NULL,
		[DLL_Name] [varchar](20) NULL,
		[Class_Module] [varchar](50) NULL,		
		[Designer] [varchar](50) 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_Slu_AC_Documents] PRIMARY KEY CLUSTERED 
		(
			[Slu_AC_Documents_ID] ASC
		)
	)
	
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Active]', @objname = N'[dbo].[Slu_AC_Documents].[Slu_AW_Active_ID]'

	EXECUTE sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[Slu_AC_Documents].[Date_Captured]'

	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_Companies]', @objname = N'[dbo].[Slu_AC_Documents].[AW_User_Companies_ID]'
	
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_ID]', @objname = N'[dbo].[Slu_AC_Documents].[User_ID]'

END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '<None>'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('<None>', '<None>', '<None>', '<None>')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '1   Continuous BT1 (2032x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('1   Continuous BT1 (2032x2032mm)', 'SpSPOSPrint3', 'C2032x2032PreBT1', 'rptT2032x2032PreBT1')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '2   Continuous BT2 (2032x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('2   Continuous BT2 (2032x2032mm)', 'SpSPOSPrint3', 'C2032x2032PreBT2', 'rptT2032x2032PreBT2')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '3   Continuous PP (2140x2165mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('3   Continuous PP (2140x2165mm)', 'SpSPOSPrint1', 'C2140x2165Pre', 'rptT2140x2165Pre')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '4   Continuous Blank (2410x2800mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('4   Continuous Blank (2410x2800mm)', 'SpSPOSPrint2', 'CEyeLineBlankA4', 'rptTCutSheetBlankA4')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '5   Continuous PP Blank (2410x2800mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('5   Continuous PP Blank (2410x2800mm)', 'SpSPOSPrint2', 'CEyeLinePreA4', 'rptTEyeLinePreA4')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '6   Cutsheet Blank A4 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('6   Cutsheet Blank A4 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetBlankA4', 'rptTCutSheetBlankA4')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '7   Cutsheet PP A4 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('7   Cutsheet PP A4 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetPreA4', 'rptTCutSheetPreA4')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '8   Continuous KOE (2160x2970mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('8   Continuous KOE (2160x2970mm)', 'SpSPOSPrint3', 'C2160x2040KOE', 'rptT2160x2040KOE')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '9   Continuous No Name (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('9   Continuous No Name (2160x2032mm)', 'SpSPOSPrint1', 'C2160x2040Std', 'rptT2160x2040Std')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '10 Continuous PP1 (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('10 Continuous PP1 (2160x2032mm)', 'SpSPOSPrint1', 'C2160x2040Pre1', 'rptT2160x2040Pre1')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '11 Continuous PP2 (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('11 Continuous PP2 (2160x2032mm)', 'SpSPOSPrint1', 'C2160x2040Pre2', 'rptT2160x2040Pre2')
End
GO
		
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '12 Continuous No Name (2032x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('12 Continuous No Name (2032x2032mm)', 'SpSPOSPrint1', 'C2000x2040Std', 'rptT2000x2040Std')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '13 Continuous PP1 (2032x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('13 Continuous PP1 (2032x2032mm)', 'SpSPOSPrint1', 'C2000x2040Pre1', 'rptT2000x2040Pre1')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '14 Continuous PP2 (2032x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('14 Continuous PP2 (2032x2032mm)', 'SpSPOSPrint1', 'C2000x2040Pre2', 'rptT2000x2040Pre2')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '15 Cutsheet Logo A4 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('15 Cutsheet Logo A4 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetLogoA4', 'rptTCutSheetLogoA4')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '16 Continuous EK2 Job (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('16 Continuous EK2 Job (2160x2032mm)', 'SpSPOSPrint3', 'C2032x2032EK', 'rptT2032x2032EK')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '17 Continuous TP1 Job (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('17 Continuous TP1 Job (2160x2032mm)', 'SpSPOSPrint3', 'C2000x2040Pre1TP', 'rptT2000x2040Pre1TP')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '18 Continuous AP1 (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('18 Continuous AP1 (2160x2032mm)', 'SpSPOSPrint3', 'C2000x2040AP', 'rptT2000x2040AP')
End
GO
 			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '19 Epson TM-T88x Receipt (80mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('19 Epson TM-T88x Receipt (80mm)', 'SpSOPOSPrint', 'CEpsonT88III', 'CEpsonT88III')
End
GO
 			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '20 Cutsheet DA Logo A4 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('20 Cutsheet DA Logo A4 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutLetterheadA4', 'rptTCutLetterheadA4')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '21 Continuous TC1 (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('21 Continuous TC1 (2160x2032mm)', 'SpSPOSPrint3', 'C2160x2032PreTC1', 'rptT2160x2032PreTC1')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '22 Continuous TC2 Moz (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('22 Continuous TC2 Moz (2160x2032mm)', 'SpSPOSPrint3', 'C2160x2032PreTC2', 'rptT2160x2032TC2')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '23 Continuous AP1 PP (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('23 Continuous AP1 PP (2160x2032mm)', 'SpSPOSPrint3', 'C2000x2040AP1', 'rptT2000x2040AP1')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '24 Cutsheet Logo A4 TC3 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('24 Cutsheet Logo A4 TC3 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetLogoA4TC3', 'rptTCutSheetLogoA4TC3')
End
GO
 			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '25 Continuous T2 (2160x2032mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('25 Continuous T2 (2160x2032mm)', 'SpSPOSPrint1', 'C2160x2032PreT2', 'rptT2160x2032PreT2')
End
GO
 			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '26 Cutsheet Logo A4JT (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('26 Cutsheet Logo A4JT (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetLogoA4F', 'rptTCutSheetLogoA4F')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '27 Continuous PPI Mac (2790x2140mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('27 Continuous PPI Mac (2790x2140mm)', 'SpSPOSPrint1', 'C2240x2795MacPre1', 'rptT2240x2795MacPre1')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '28 Continuous PPQ Mac (2790x2140mm)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('28 Continuous PPQ Mac (2790x2140mm)', 'SpSPOSPrint1', 'C2240x2795MacPre2', 'rptT2240x2795MacPre2')
End
GO
			
IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '29 Cutsheet Blank A4 Mac (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('29 Cutsheet Blank A4 Mac (Laser/InkJet)', 'SpSPOSPrint2', 'CMacBlankA4', 'rptTMacBlankA4')
End
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Slu_AC_Documents
	WHERE Document_Layout = '30 Cutsheet Logo A4 TC4 (Laser/InkJet)'
)
Begin
	INSERT INTO Slu_AC_Documents(Document_Layout, DLL_Name, Class_Module, Designer)
	VALUES('30 Cutsheet Logo A4 TC4 (Laser/InkJet)', 'SpSPOSPrint2', 'CCutSheetLogoA4TC4', 'rptTCutSheetLogoA4TC4')
End
GO
			
--Invoice Details
--AC_Customers Slu_AC_Documnets_ID_Invoice
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='AC_Customers' AND
		C.Name='Slu_AC_Documnets_ID_Invoice'
) 
	ALTER TABLE AC_Customers ADD Slu_AC_Documnets_ID_Invoice tinyint NULL
	GO	          
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AC_Documnets_ID_Invoice]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Slu_AC_Documnets_ID_Invoice = 1
	WHERE Slu_AC_Documnets_ID_Invoice IS NULL	
	GO
	
--AC_Customers Invoice_Printer
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='AC_Customers' AND
		C.Name='Invoice_Printer'
) 
	ALTER TABLE AC_Customers ADD Invoice_Printer Varchar(100) NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Invoice_Printer]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Invoice_Printer = ''
	WHERE Invoice_Printer IS NULL	
	GO

--AC_Customers Invoice_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='AC_Customers' AND
		C.Name='Invoice_Email'
) 
	ALTER TABLE AC_Customers ADD Invoice_Email Varchar(80) NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Invoice_Email]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Invoice_Email = ''
	WHERE Invoice_Email IS NULL	
	GO

--AC_Customers AW_YesNo_Invoice_TCS
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='AC_Customers' AND
		C.Name='AW_YesNo_Invoice_TCS'
) 
	ALTER TABLE AC_Customers ADD AW_YesNo_Invoice_TCS tinyint NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Invoice_TCS]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET AW_YesNo_Invoice_TCS = 0
	WHERE AW_YesNo_Invoice_TCS IS NULL	
	GO

--Quote Details
--AC_Customers Slu_AC_Documents_ID_Quote
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='AC_Customers' AND
		C.Name='Slu_AC_Documents_ID_Quote'
) 
	ALTER TABLE AC_Customers ADD Slu_AC_Documents_ID_Quote tinyint NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AC_Documents_ID_Quote]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Slu_AC_Documents_ID_Quote = 1
	WHERE Slu_AC_Documents_ID_Quote IS NULL	
	GO

--AC_Customers Quote_Printer
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='AC_Customers' AND
		C.Name='Quote_Printer'
) 
	ALTER TABLE AC_Customers ADD Quote_Printer Varchar(100) NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Quote_Printer]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Quote_Printer = ''
	WHERE Quote_Printer IS NULL	
	GO
	
--AC_Customers Quote_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='AC_Customers' AND
		C.Name='Quote_Email'
) 
	ALTER TABLE AC_Customers ADD Quote_Email Varchar(80) NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Quote_Email]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET Quote_Email = ''
	WHERE Quote_Email IS NULL	
	GO
	
--AC_Customers AW_YesNo_Quote_TCS
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='AC_Customers' AND
		C.Name='AW_YesNo_Quote_TCS'
) 
	ALTER TABLE AC_Customers ADD AW_YesNo_Quote_TCS tinyint NULL
	GO        
	-------------------------------------------------------
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Quote_TCS]'
	-------------------------------------------------------
	GO
	UPDATE AC_Customers
	SET AW_YesNo_Quote_TCS = 0
	WHERE AW_YesNo_Quote_TCS IS NULL	
	GO

--25_2 alt_AC_Customers Default_Email_Settings
--Add automatic email setting for customers
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='AC_Customers' AND
        C.Name='Slu_AC_Documents_ID_Invoice'
) 
ALTER TABLE AC_Customers ADD Slu_AC_Documents_ID_Invoice tinyint NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AC_Documents_ID_Invoice]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Slu_AC_Documents_ID_Invoice = 1
WHERE Slu_AC_Documents_ID_Invoice IS NULL	
GO

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='AC_Customers' AND
        C.Name='Invoice_Printer'
) 
ALTER TABLE AC_Customers ADD Invoice_Printer varchar(100) NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Invoice_Printer]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Invoice_Printer = ''
WHERE Invoice_Printer IS NULL	
GO

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='AC_Customers' AND
        C.Name='Invoice_Email'
) 
ALTER TABLE AC_Customers ADD Invoice_Email varchar(80) NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Invoice_Email]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Invoice_Email = ''
WHERE Invoice_Email IS NULL	
GO

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='AC_Customers' AND
        C.Name='AW_YesNo_Invoice_TCS'
) 
ALTER TABLE AC_Customers ADD AW_YesNo_Invoice_TCS tinyint NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Invoice_TCS]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET AW_YesNo_Invoice_TCS = 0
WHERE AW_YesNo_Invoice_TCS IS NULL	
GO


--Add automatic email setting for customers
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='AC_Customers' AND
        C.Name='Slu_AC_Documents_ID_Quote'
) 
ALTER TABLE AC_Customers ADD Slu_AC_Documents_ID_Quote tinyint NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[Slu_AC_Documents_ID_Quote]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Slu_AC_Documents_ID_Quote = 1
WHERE Slu_AC_Documents_ID_Quote IS NULL	
GO

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='AC_Customers' AND
        C.Name='Quote_Printer'
) 
ALTER TABLE AC_Customers ADD Quote_Printer varchar(100) NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Quote_Printer]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Quote_Printer = ''
WHERE Quote_Printer IS NULL	
GO

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='AC_Customers' AND
        C.Name='Quote_Email'
) 
ALTER TABLE AC_Customers ADD Quote_Email varchar(80) NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Customers].[Quote_Email]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET Quote_Email = ''
WHERE Quote_Email IS NULL	
GO

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='AC_Customers' AND
        C.Name='AW_YesNo_Quote_TCS'
) 
ALTER TABLE AC_Customers ADD AW_YesNo_Quote_TCS tinyint NULL
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Quote_TCS]'
-------------------------------------------------------
GO
UPDATE AC_Customers
SET AW_YesNo_Quote_TCS = 0
WHERE AW_YesNo_Quote_TCS IS NULL	
GO

--26 sp_AC_Select_Customer_Catalog
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Customer_Catalog]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Customer_Catalog]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Catalog
--Purpose       :Retrieves the customer catalog data
--Functionality :Select 
--Parameters    :
--Date          :2001/12/05
--Authors       :TB
--MODS          :03/01/04 - Added 9 fields including Controller, Pre/Post Notify
--              :           Delivery Method, and Principal for Credit Manager
--              :19/06/04 - Added new [Send Email] field
--              :05/07/04 - Added new [Customer_Group] field
--              :03/02/05 - Added new [SettleDisc] field
--2004.3.2      :11/10/06 - Added new [NetBilling] and [PurchaseOrder] fields
--2004.4.0      :24/07/07 - Added new [CostPlusBilling] field
--              :25/07/07 - Added new [CostPlusCategory] field
--2004.4.5      :13/06/09 - Added new [OverrideLimit] and [OverrideOverdue] field
--2004.5.2      :03/06/11 - Added new AW_YesNo_Attach_Tran_ID AS [Attach Docs]
--2004.4.9 RL   :2013-07-08 - Added AW_YesNo_Apply_Product_Levy
--RL	V6.0	:2014-04-21 - Added Automatically email documnets fields
----------------------------------------------------------------------------

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

SET NOCOUNT ON

SELECT
        AC_Customers_ID AS [ID], 
        Surname AS [Name], 
        Firstnames AS [First Names], 
        Initials AS [Initials], 
        Slu_AW_Titles_ID AS Title, 
        Slu_AW_Languages_ID AS Language, 
        IDReg_Number AS [ID/Reg No], 
        Start_Date AS [Start Date], 
        Customer_Number AS [Customer No], 
        Old_Customer_Number AS [Old Customer No], 
        Head_Office AS [Head Office], 
        Lup_AC_Customer_Types_ID AS [Customer_Type], 
        Lup_AC_Customer_Groups_ID AS [Customer_Group], 
        Sys_AC_Use_Assets_ID AS [Use Assets],
        Sys_AW_Delivery_Methods_ID AS [Method],
        Sys_AW_Tax_Codes_ID AS [Tax Code], 
        Tax_Number AS [Tax Number],
        Notes, 
        Lup_AC_Discount_Categories_ID AS [Sales Discount], 
        Credit_Limit AS [Credit Limit], 
        Slu_AW_Credit_Terms_ID AS [Credit Terms], 
        Sys_AC_Credit_Term_Types_ID AS [Credit Term Types],
        Credit_Insurers_Reference AS [Credit Insurers Ref],
        Credit_Insurers_Limit AS [Credit Insurers Limit],
        AW_YesNo_Charge_Interest_ID AS [Charge Interest],
        Slu_AW_Controllers_ID AS [Controller], 
        AW_YesNo_Pre_Notify_ID AS [PreNotify], 
        AW_YesNo_Post_Notify_ID AS [PostNotify], 
        Lup_AS_Reps_ID AS Salesperson, 
        Lup_AC_Sales_Areas_ID AS [Sales Areas], 
        Contact_Name AS [Contact Name], 
        Sys_AC_Account_Types_ID AS [Account Types],
        Sys_AC_Account_Status_ID AS [Account Status],
        Slu_AW_Active_ID AS Active, 
        Post_Box AS [Post Box], 
        Post_Office AS [Post Office], 
        Post_Code AS [Post Code], 
        Street_Address AS [Street Address], 
        Suburb AS [Suburb], 
        City AS [City], 
        Street_Post_Code AS [Street Code], 
        Delivery_Address AS [Delivery Address], 
        Delivery_Suburb AS [Delivery Suburb], 
        Delivery_City AS [Delivery City], 
        Delivery_Post_Code AS [Delivery Post Code], 
        Slu_AW_Countries_ID AS [Country], 
        Home_Tel_No AS [Home Tel No], 
        Work_Tel_No AS [Work Tel No], 
        Cell_No AS [Cell No], 
        Fax_No AS [Fax No], 
        Principal_Name AS [Principal Name],
        Principal_Firstname AS [Principal Firstname],
        Principal_Birthday AS [Principal Birthday],
        Principal_Contact_Method_ID AS [PrincipalMethod],
        Principal_Cell_No AS [PrincipalCellNo],
        Web_Site_URL AS [Web Site URL], 
        Orders_URL AS [Order URL], 
        Home_Email AS [E-mail Home], 
        Work_Email AS [E-mail Work], 
        Account_Balance AS [Account Balance],
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company ID],
        AW_YesNo_Send_Email_ID AS [Send Email],
        AW_YesNo_Attach_Tran_ID AS [Attach Docs],
        Default_Settlement_Discount AS [SettleDisc],
        AW_YesNo_Net_Billing_ID AS [NetBilling], 
        AW_YesNo_Purchase_Order_ID AS [PurchaseOrder],
        AW_YesNo_CostPlus_Billing_ID AS [CostPlusBilling],
        Lup_AC_Markup_Categories_ID AS [CostPlusCategory],
        AW_YesNo_Override_Credit_Limit AS [OverrideLimit],
        AW_YesNo_Override_Overdue AS [OverrideOverdue],
        AW_YesNo_Apply_Product_Levy As [Apply_Product_Levy],
        AW_YesNo_Change_Doc_Details As [Change_Doc_Details],
	Slu_AC_Documents_ID_Invoice As [Invoice_Document],    
	Invoice_Printer As [Invoice_Printer],
	Invoice_Email As [Invoice_Email],
	AW_YesNo_Invoice_TCS As [Invoice_TCS],
	Slu_AC_Documents_ID_Quote As [Quote_Document],
	Quote_Printer As [Quote_Printer],
	Quote_Email As [Quote_Email],
	AW_YesNo_Quote_TCS As [Quote_TCS]        
FROM AC_Customers 
WHERE AC_Customers_ID = @CustomerID AND
      AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF
GO

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

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

    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

        UNION

        SELECT Home_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID

        UNION

        SELECT Work_Email as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID

    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

END  
GO

--28 sp_AC_Select_Customer_Document
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Customer_Document]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Customer_Document]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Document
--Purpose       :Retrieves the customer email document details
--Functionality :Select 
--Parameters    :
--Date          :2014/04/21
--Authors       :RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Document]
    (
        @CustomerID int,
        @TransactionID int
    )
AS

SET NOCOUNT ON

	Declare @DocNo	Varchar(20)
	Declare @Comapny_Email	Varchar(80)

	Set @DocNo = ''
	Set @Comapny_Email = ''
	
	Select @DocNo = Transaction_Number
	From AS_Transactions
	Where AS_Transactions_ID = @TransactionID

	SELECT TOP 1 @Comapny_Email = ISNULL(E_Mail, '')
	FROM AW_User_Companies

	SELECT
        i.Document_Layout As [Invoice_Document_Layout],
		i.DLL_Name As [Invoice_DLL],
		i.DLL_Name + '.' + i.Class_Module As [Invoice_Class_Module],		
		Invoice_Printer As [Invoice_Printer],
		Invoice_Email As [Invoice_Email],
		AW_YesNo_Invoice_TCS As [Invoice_TCS],
		
        q.Document_Layout As [Quote_Document_Layout],
		q.DLL_Name As [Quote_DLL],
		q.DLL_Name + '.' + Q.Class_Module As [Quote_Class_Module],			
		Quote_Printer As [Quote_Printer],
		Quote_Email As [Quote_Email],
		AW_YesNo_Quote_TCS As [Quote_TCS],
		
		@DocNo As [DocNo],
		@Comapny_Email As [Comapny_Email]        
	FROM AC_Customers c
	LEFT OUTER JOIN Slu_AC_Documents i
		ON c.Slu_AC_Documents_ID_Invoice = i.Slu_AC_Documents_ID
	LEFT OUTER JOIN Slu_AC_Documents q
		ON c.Slu_AC_Documents_ID_Quote = q.Slu_AC_Documents_ID	
	WHERE AC_Customers_ID = @CustomerID

SET NOCOUNT OFF
GO

--29 alt_AS_Enterprise_Sales_Quantity
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_Enterprise_Sales' AND
        C.Name='Quantity'
) 
ALTER TABLE AS_Enterprise_Sales ADD Quantity DECIMAL (12, 3) NULL
Go

--30 PK_AP_Inventory_Valuations
--Check to see if Primary key exists on AP_Inventory_Valuations table
IF NOT EXISTS
(
	SELECT * 
	FROM sysobjects 
	WHERE xtype = 'PK' 
	AND name = 'PK_AP_Inventory_Valuations'
)
	ALTER TABLE AP_Inventory_Valuations
	ADD CONSTRAINT PK_AP_Inventory_Valuations PRIMARY KEY CLUSTERED (AP_Inventory_Valuations_ID)
GO

--31 Delete_Duplicate_Menue_Items
-----------------------------------------------------------------
-- 1. Removes Duplicate Application Menue Items
-- RL
-- 2014-04-24
-----------------------------------------------------------------

Declare @Sys_AW_Applications_ID	Int, 
		@Description			Varchar(50), 
		@Sys_AW_Modules_ID		Int

SET NOCOUNT ON

DECLARE Select_Customers CURSOR FOR
(
	SELECT Sys_AW_Applications_ID, [Description], Sys_AW_Modules_ID
	FROM Sys_AW_Applications

)
   
OPEN Select_Customers

FETCH NEXT FROM Select_Customers 
INTO @Sys_AW_Applications_ID, @Description, @Sys_AW_Modules_ID
    	
WHILE @@FETCH_STATUS = 0
BEGIN
    
	IF Exists
	(
		SELECT 1
		FROM Sys_AW_Applications
		WHERE [Description] = @Description
		AND Sys_AW_Modules_ID = @Sys_AW_Modules_ID
		AND Slu_AW_Active_ID = 1
		AND Sys_AW_Applications_ID <> @Sys_AW_Applications_ID
	)
	BEGIN
		DELETE AW_Applications_Per_Role WHERE Sys_AW_Applications_ID = @Sys_AW_Applications_ID
	
		DELETE Sys_AW_Applications WHERE Sys_AW_Applications_ID = @Sys_AW_Applications_ID
	END


	FETCH NEXT FROM Select_Customers 
	INTO @Sys_AW_Applications_ID, @Description, @Sys_AW_Modules_ID    
END
    	
CLOSE Select_Customers
DEALLOCATE Select_Customers
GO

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

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]

--	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
	WHERE t.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF
GO

--33 Sys_AC_Status
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[Sys_AC_Status]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	CREATE TABLE [dbo].[Sys_AC_Status]
	(
		[Sys_AC_Status_ID] [int] IDENTITY(1,1) NOT NULL,
		[Field1] [varchar](200) NULL,	--S ID		
		[Field2] [varchar](200) NULL,	--Server
		[Field3] [varchar](200) NULL,	--DB
		[Field4] [varchar](200) NULL,	--Computer Name
		[Field5] [varchar](200) NULL,	--App
		[Field6] [varchar](200) NULL,	--User
		[Field7] [varchar](200) NULL,	--Module
		[Field8] [varchar](200) NULL,	--Mac ADD
		[Field9] [varchar](200) NULL,	--Key
		[Field10] [varchar](200) NULL,	--App Ver And DB Ver
		[Field11] [varchar](200) NULL,	--SQL Ver			
		[Field12] [int] NULL,	--Sent					
		[Date_Captured] DateTime NULL																
		CONSTRAINT [PK_Sys_AC_Status] PRIMARY KEY CLUSTERED 
		(
			[Sys_AC_Status_ID] ASC
		)
	)
	
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[Sys_AC_Status].[Date_Captured]'	
	
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_Zero]', @objname = N'[dbo].[Sys_AC_Status].[Field12]'		
	
	CREATE INDEX InxSys_AC_Status_12 on Sys_AC_Status(Field12)
END
GO

--34 sp_Sys_AC_Status_Insert
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_Sys_AC_Status_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Sys_AC_Status_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Insert
--Purpose       :INSERT Sys_AC_Status
--Parameters    :
--Date          :2014-04-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Insert]
	(
		@Field1 [varchar](200),	--S ID		
		@Field2 [varchar](200),	--Server
		@Field3 [varchar](200),	--DB
		@Field4 [varchar](200),	--Computer Name
		@Field5 [varchar](200),	--App
		@Field6 [varchar](200),	--User
		@Field7 [varchar](200),	--Module
		@Field8 [varchar](200),	--Mac ADD
		@Field9 [varchar](200),	--Key
		@Field10 [varchar](200), --APP, DB Ver
		@Field11 [varchar](200)  --SQL Ver
	)
AS

SET NOCOUNT ON    

    INSERT Sys_AC_Status
        (
            Field1,
            Field2,
            Field3,
            Field4,
            Field5,
            Field6,
            Field7,
            Field8,
            Field9,
            Field10,
            Field11,
            Date_Captured
        )
    VALUES
        (
            @Field1,
            @Field2,
            @Field3,
            @Field4,
            @Field5,
            @Field6,
            @Field7,
            @Field8,
            @Field9,
            @Field10,
            @Field11,
            GETDATE()
        )

SET NOCOUNT OFF
Go

--35 sp_Sys_AC_Status_Mark
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_Sys_AC_Status_Mark]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Sys_AC_Status_Mark]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Mark
--Purpose       :Update Sys_AC_Status Status
--Parameters    :
--Date          :2014-04-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Sys_AC_Status_Mark]
	(
		@From_Status	Int,
		@ToStatus		Int
	)
AS

SET NOCOUNT ON    

    UPDATE Sys_AC_Status
    SET Field12 = @ToStatus
    Where Field12 = @From_Status

SET NOCOUNT OFF
GO

--36 Insert Status FTP Details
--Insert Status FTP Details
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtSPFTPUserName'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtSPFTPUserName',
		0,
		'AdvReports',
		Getdate(),
		1,
		1
	)
END
GO

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

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

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

--37 sp_Sys_AC_Status_Get
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
-------------------------------------------------------------------------------
--Description   :sp_Sys_AC_Status_Get
--Purpose       :Get Sys_AC_Status
--Parameters    :
--Date          :2014-05-03
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

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)	
			
	DECLARE @Tbl Table
		(
			UniqueID [int] IDENTITY(1,1) PRIMARY KEY,		
			[Rec] [varchar](8000)
		)
		
	SELECT @DB = DB_NAME() 		
	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],''),'~','')
	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
			
	IF Exists	
	(
		SELECT 1
		FROM AS_Day_ENDs
	)
	BEGIN 
		SELECT @LastDayEND = MAX(Day_END) FROM AS_Day_ENDs
		SELECT @LastDayEND = DateAdd(d,-5,@LastDayEND)
	END
	ELSE
	BEGIN		
		SELECT @LastDayEND = '1900-01-01'
	END

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

	--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),t.AS_Transactions_ID) + '~' + 
		Convert(varchar(10),t.Transaction_Number) + '~' + 
		Convert(varchar(10),t.Transaction_Date,120) + '~' + 
		Convert(varchar(2),t.Sys_AW_Transaction_Types_ID) + '~' + 		
		Convert(varchar(18),t.Total_Cost) + '~' + 
		Convert(varchar(18),t.Amount) + '~' + 
		Convert(varchar(18),t.Total_Tax_Amount) + '~' + 
		Convert(varchar(18),t.Total_Discount_Amount) + '~' + 
		Convert(varchar(18),t.Total_Amount) + '~' + 
		Convert(varchar(18),t.Payment_Amount) + '~' + 
		Replace(IsNull(t.Customer_Reference,''),'~','') + '~' + 
		Replace(IsNull(t.Comment,''),'~','') + '~' + 		
		Convert(varchar(10),t.[User_ID]) + '~' + 
		Replace(IsNull(u.FirstName,''),'~','') + ' ' + Replace(IsNull(u.Surname,''),'~','') + '~' + 
		Replace(IsNull(u.[UserName],''),'~','') + '~' + 
		Convert(varchar(10),t.Lup_AS_Reps_ID) + '~' + 
		Case IsNull(tr.[Description],'') --Transaction Rep
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(tr.[Description],''),'~','')
		END + '~' + 
		Convert(varchar(5),c.Lup_AS_Reps_ID) + '~' + --Customer Rep
		Case IsNull(cr.[Description],'')
		When '<SELECT>' Then '1'
		When '<None>' Then '1'
		ELSE Replace(IsNull(cr.[Description],''),'~','')
		END + '~' + 
		Convert(varchar(2),c.Sys_AC_Account_Types_ID) + '~' + 
		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,''),'~','')	
	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	
	WHERE 
		(	t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
			t.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds		
	t.Slu_AW_Active_ID = 1 AND
	t.Transaction_Date > @LastDayEND

	INSERT INTO @Tbl
	SELECT
		'D'  + '~' + 
		Convert(varchar(10),t.AS_Transactions_ID) + '~' + 
		Convert(varchar(10),d.AS_Transaction_Details_ID) + '~' + 
		Convert(varchar(10),d.AP_Products_ID) + '~' + 
		Convert(varchar(18),d.Quantity) + '~' + 
		Convert(varchar(18),d.Unit_Cost) + '~' + 
		Convert(varchar(18),d.Unit_Price) + '~' + 
		Convert(varchar(18),d.Original_Price) + '~' + 
		Convert(varchar(18),d.Original_Discount) + '~' + 
		Convert(varchar(18),d.Discount_Amount) + '~' + 
		Convert(varchar(18),d.Tax_Amount) + '~' + 
		Convert(varchar(18),d.Extended_Amount) + '~' + 
		Convert(varchar(10),d.AS_Job_References_ID)
	FROM AS_Transactions t
		Left Join AS_Transaction_Details d
			On t.AS_Transactions_ID = d.AS_Transactions_ID
		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	
	WHERE 
		(	t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
			t.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds		
	t.Slu_AW_Active_ID = 1 AND
	t.Transaction_Date > @LastDayEND

	--Insert Product Records
	INSERT INTO @Tbl
	SELECT
		'P'  + '~' + 
		Convert(varchar(10),p.AP_Products_ID) + '~' + 
		Replace(IsNull(p.[Description],''),'~','') + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' + 
		Replace(IsNull(p.Manufacturer_Code,''),'~','') + '~' + 
		Replace(IsNull(m.[Description],''),'~','') + '~' + 
		Convert(varchar(18),IsNull(p.Last_Cost,0)) + '~' + 
		Convert(varchar(18),IsNull(p.Average_Cost,0)) + '~' + 
		Convert(varchar(18),IsNull(p.Standard_Cost,0)) + '~' + 
		Convert(varchar(10),IsNull(p.Price1_Effective_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(18),IsNull(p.Price1_Price1,0)) + '~' + 
		Convert(varchar(1),IsNull(p.Slu_AW_YesNo_Non_Stock_Item,3)) + '~' + 
		Convert(varchar(1),IsNull(p.Slu_AW_YesNo_Levy_Item,3)) + '~' + 
--		Convert(varchar(10),IsNull(p.Service_Level,0)) + '~' + 
--		Convert(varchar(10),IsNull(p.Min_Stock_Level,0)) + '~' + 	
--		Convert(varchar(10),IsNull(p.Max_Order_Qty,0)) + '~' + 
--		Convert(varchar(10),IsNull(p.Min_Order_Qty,0)) + '~' + 
		Convert(varchar(10),IsNull(p.On_Hand,0)) --+ '~' + 
--		Convert(varchar(10), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) + '~' + --Includes Sales Orders
--		Convert(varchar(10), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID))
	FROM AP_Products p
		Inner Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
	WHERE On_Hand <> 0		
	Union
	SELECT
		'P'  + '~' + 
		Convert(varchar(10),p.AP_Products_ID) + '~' + 
		Replace(IsNull(p.[Description],''),'~','') + '~' + 
		Replace(IsNull(p.Product_Code,''),'~','') + '~' + 
		Replace(IsNull(p.Manufacturer_Code,''),'~','') + '~' + 
		Replace(IsNull(m.[Description],''),'~','') + '~' + 
		Convert(varchar(18),IsNull(p.Last_Cost,0)) + '~' + 
		Convert(varchar(18),IsNull(p.Average_Cost,0)) + '~' + 
		Convert(varchar(18),IsNull(p.Standard_Cost,0)) + '~' + 
		Convert(varchar(10),IsNull(p.Price1_Effective_Date,'1900-01-01'),120) + '~' + 
		Convert(varchar(18),IsNull(p.Price1_Price1,0)) + '~' + 
		Convert(varchar(1),IsNull(p.Slu_AW_YesNo_Non_Stock_Item,3)) + '~' + 
		Convert(varchar(1),IsNull(p.Slu_AW_YesNo_Levy_Item,3)) + '~' + 
--		Convert(varchar(10),IsNull(p.Service_Level,0)) + '~' + 
--		Convert(varchar(10),IsNull(p.Min_Stock_Level,0)) + '~' + 	
--		Convert(varchar(10),IsNull(p.Max_Order_Qty,0)) + '~' + 
--		Convert(varchar(10),IsNull(p.Min_Order_Qty,0)) + '~' + 
		Convert(varchar(10),IsNull(p.On_Hand,0)) --+ '~' + 
--		Convert(varchar(10), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) + '~' + --Includes Sales Orders 
--		Convert(varchar(10), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID))
	FROM AP_Products p
		Inner Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
	WHERE On_Hand <> 0		
	AND p.AP_Products_ID In (
								SELECT d.AP_Products_ID
								FROM AS_Transactions t
									Left Join AS_Transaction_Details d
										On t.AS_Transactions_ID = d.AS_Transactions_ID
								WHERE 
									(	t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
										t.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds		
								t.Slu_AW_Active_ID = 1 AND
								t.Transaction_Date > @LastDayEND
							)
							
	--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 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
	FROM
		Sys_AC_Status
	WHERE
		ISNULL(Field12,0) = 1

	SELECT Rec FROM @Tbl ORDER BY UniqueID


SET NOCOUNT OFF
GO

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

-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Product_Update
--Purpose       :INSERT Product Update into target DB
--Date          :2006/06/01
--Authors       :TB
--MODS:         :
--2004.3.0      :11/07/06 - Removed RTRIM/LTRIM formatting in fetch criteria
--              :13/07/06 - Fixed assignment of @DateCaptured to Manufacturer_Code
--              :           and Manufacturer_Description in the UPDATE section
--2004.3.2      :11/09/06 - Removed update of Last_Cost and Average_Cost fields
--              :11/09/06 - Added @LocationID input parameter and update [Location] field
--              :30/09/06 - Added IF EXISTS condition to verify if this update product's
--              :           Lup_AP_Product_Manufacturers_ID = @ManufID before UPDATE
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :29/12/06 - Reworked INSERT/UPDATE section of the UPDATE PRODUCT to FIRST
--              :           fetch its Product_ID and test if it EXISTS (if value > 0)
--              :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.3.5      :26/04/07 - Modified WHERE clause in IF EXISTS @ProductID to SELECT
--              :           @ProductCode and @DateCaptured only
--              :31/05/07 - Modified WHERE clause in IF EXISTS @ProductID to STRIP
--              :           milliseconds from Date_Captured and @DateCaptured
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--              :15/04/08 - Replaced [@MaxDisc] with [@MinGP] and [@ApplyMaxID] with [@ApplyMinID]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--              :10/03/11 - Replaced get top 1 LookupID if Lookup does not exist
--              :           with INSERT LOOKUP if NOT EXISTS LOOKUP
--2004.5.2      :11/07/11 - Fixed @Supplier field length to new size 40 !!!!
--2004.5.3      :08/09/11 - Modified to fetch update product on code and date captured
--              :           now ONLY IF the product is ACTIVE - SHOULD PUT IN A CURSOR !!!!!!!!!
--              :20/09/11 - Modified fetch LOOKUPS to assign FIRST LOOKUP ID if @LookupDesc = BLANK
--2004.5.7 RGL	:2012-11-01 - Added Levy and Weight
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Product_Update]
	(
        @Description varchar(50), --1
        @ProductCode varchar(20), --2
        @Size decimal(9, 3), --3
        @DateCaptured datetime, --4
        @SKUCode varchar(20), --5
        @AltCode1 varchar(20), --6
        @BarCode varchar(20), --7
        @Manuf varchar(30), --8
        @ManufCode varchar(20), --9
        @ManufDesc varchar(50), --10
        @Supplier varchar(40), --11
        @Type varchar(50), --12
        @Group varchar(50), --13
        @Dept varchar(50), --14
        @Location varchar(50), --15
        @PurchaseCat varchar(50), --16
        @LastCost money, --17
        @AvgCost money, --18
        @StdCost money, --19
        @Price1Date datetime, --20
        @Price11 money, --21
        @Price12 money, --22
        @Price2Date datetime, --23
        @Price21 money, --24
        @Price22 money, --25
        @PackVolume decimal(9, 3), --26
        @PackMass decimal(9, 3), --27
        @ActiveID tinyint, --28
        @EditPriceID tinyint, --29
        @EditDiscID tinyint, --30
        @MinGP decimal(5, 2), --31
        @ApplyMinID tinyint, --32
        @chkUpdProtector tinyint, --33
                
        @Levy varchar(50), --34
        @WeightType varchar(50), --35
        @Weight decimal(9, 3), --36

        @CompanyID int, --37
        @UserID int --38
	)

AS

SET NOCOUNT ON

	DECLARE @ManufID int,
            @SupplierID int,
            @TypeID int,
            @GroupID smallint,
            @DeptID int,
            @LocationID int,
            @PurchaseCatID int,
            @RetCode int,
            @ProductID int,
            @LevyID int,
            @WeightTypeID int


    SET @RetCode = 0

	SET @Manuf = RTRIM(LTRIM(ISNULL(@Manuf,'')))
	SET @Supplier = RTRIM(LTRIM(ISNULL(@Supplier,'')))
	SET @Type = RTRIM(LTRIM(ISNULL(@Type,'')))
	SET @Group = RTRIM(LTRIM(ISNULL(@Group,'')))
	SET @Dept = RTRIM(LTRIM(ISNULL(@Dept,'')))
	SET @Location = RTRIM(LTRIM(ISNULL(@Location,'')))
	SET @PurchaseCat = RTRIM(LTRIM(ISNULL(@PurchaseCat,'')))
	SET @WeightType = RTRIM(LTRIM(ISNULL(@WeightType,'')))
	SET @Levy = RTRIM(LTRIM(ISNULL(@Levy,'')))
	Set @Description = RTRIM(LTRIM(ISNULL(@Description,'')))
	
    ---------------------------------------------------------
    --> FIND the ID of the LOOKUP if ACTIVE or INSERT NEW
    ---------------------------------------------------------
    --> Get Manufacturer ID
    --Select @Manuf As '@Manuf'
    SET @ManufID = NULL
    IF @Manuf = ''
        BEGIN
			SET @ManufID = 0
            SELECT TOP 1 @ManufID = Lup_AP_Product_Manufacturers_ID
            FROM Lup_AP_Product_Manufacturers
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @ManufID = 0
    BEGIN
		SET @Manuf = '<None>'
    END
    
    IF @Manuf <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Manufacturers_ID
                    FROM Lup_AP_Product_Manufacturers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Manuf AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Manufacturers (Description, AW_User_Companies_ID) VALUES (@Manuf, @CompanyID)

        			SELECT @ManufID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @ManufID = Lup_AP_Product_Manufacturers_ID
                    FROM Lup_AP_Product_Manufacturers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Manuf AND
                          Slu_AW_Active_ID = 1
                END
        END
--Select @ManufID As '@ManufID'

    --> Get Supplier ID
    SET @SupplierID = NULL
    IF @Supplier = ''
        BEGIN
			SET @SupplierID = 0
            SELECT TOP 1 @SupplierID = AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  LTRIM(RTRIM(Supplier_Name)) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @SupplierID = 0
    BEGIN
		SET @Supplier = '<None>'
    END
    
    IF @Supplier <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT AO_Suppliers_ID
                    FROM AO_Suppliers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          LTRIM(RTRIM(Supplier_Name)) = @Supplier AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT AO_Suppliers (Supplier_Name, AW_User_Companies_ID) VALUES (@Supplier, @CompanyID)

        			SELECT @SupplierID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @SupplierID = AO_Suppliers_ID
                    FROM AO_Suppliers
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          LTRIM(RTRIM(Supplier_Name)) = @Supplier AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Type ID
    SET @TypeID = NULL
    IF @Type = ''
        BEGIN
			SET @TypeID = 0
            SELECT TOP 1 @TypeID = Lup_AP_Product_Types_ID
            FROM Lup_AP_Product_Types
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @TypeID = 0
    BEGIN
		SET @Type = '<None>'
    END
    
    IF @Type <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Types_ID
                    FROM Lup_AP_Product_Types
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Type AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Types (Description, AW_User_Companies_ID) VALUES (@Type, @CompanyID)

        			SELECT @TypeID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @TypeID = Lup_AP_Product_Types_ID
                    FROM Lup_AP_Product_Types
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Type AND
                          Slu_AW_Active_ID = 1
                END
        END

    --> Get Product Group ID
    SET @GroupID = NULL
    IF @Group = ''
        BEGIN
			SET @GroupID = 0
            SELECT TOP 1 @GroupID = Lup_AP_Product_Groups_ID
            FROM Lup_AP_Product_Groups
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @GroupID = 0
    BEGIN
		SET @Group = '<None>'
    END
    
    IF @Group <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Groups_ID
                    FROM Lup_AP_Product_Groups
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Group AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Groups (Description, AW_User_Companies_ID) VALUES (@Group, @CompanyID)

        			SELECT @GroupID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @GroupID = Lup_AP_Product_Groups_ID
                    FROM Lup_AP_Product_Groups
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Group AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Department ID
    SET @DeptID = NULL
    IF @Dept = ''
        BEGIN
			SET @DeptID = 0
            SELECT TOP 1 @DeptID = Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @DeptID = 0
    BEGIN
		SET @Dept = '<None>'      
    END
    
    IF @Dept <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Departments_ID
                    FROM Lup_AP_Product_Departments
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Dept AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Departments (Description, AW_User_Companies_ID) VALUES (@Dept, @CompanyID)

        			SELECT @DeptID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @DeptID = Lup_AP_Product_Departments_ID
                    FROM Lup_AP_Product_Departments
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Dept AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Product Location ID
    SET @LocationID = NULL
    IF @Location = ''
        BEGIN
			SET @LocationID = 0
            SELECT TOP 1 @LocationID = Lup_AP_Product_Locations_ID
            FROM Lup_AP_Product_Locations
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @LocationID = 0
    BEGIN
		SET @Location = '<None>'
    END
    
    IF @Location <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Product_Locations_ID
                    FROM Lup_AP_Product_Locations
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Location AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Product_Locations (Description, AW_User_Companies_ID) VALUES (@Location, @CompanyID)

        			SELECT @LocationID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @LocationID = Lup_AP_Product_Locations_ID
                    FROM Lup_AP_Product_Locations
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @Location AND
                          Slu_AW_Active_ID = 1
                END
        END


    --> Get Purchase Category ID
    SET @PurchaseCatID = NULL
    IF @PurchaseCat = ''
        BEGIN
			SET @PurchaseCatID = 0
            SELECT TOP 1 @PurchaseCatID = Lup_AP_Purchase_Categories_ID
            FROM Lup_AP_Purchase_Categories
            WHERE AW_User_Companies_ID = @CompanyID AND
                 LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
    
    IF @PurchaseCatID = 0
    BEGIN
		SET @PurchaseCat = '<None>'
    END
    
    IF @PurchaseCat <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_Purchase_Categories_ID
                    FROM Lup_AP_Purchase_Categories
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @PurchaseCat AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_Purchase_Categories (Description, AW_User_Companies_ID) VALUES (@PurchaseCat, @CompanyID)

        			SELECT @PurchaseCatID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @PurchaseCatID = Lup_AP_Purchase_Categories_ID
                    FROM Lup_AP_Purchase_Categories
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @PurchaseCat AND
                          Slu_AW_Active_ID = 1
                END
        END

    --> Get Levy ID
    SET @LevyID = 0
    IF @Levy <> ''
        BEGIN
            SELECT TOP 1 @LevyID = AP_Products_ID
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @CompanyID AND
    			  Slu_AW_YesNo_Levy_Item = 1 AND
    			  [Description] = @Levy
        END
    
    --> Get Weight ID
    SET @WeightTypeID = NULL
    IF @WeightType = ''
        BEGIN
			SET @WeightTypeID = 0
            SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
            FROM Lup_AP_AW_Weight
            WHERE AW_User_Companies_ID = @CompanyID AND
				  LTRIM(RTRIM([Description])) = '<None>' AND
                  Slu_AW_Active_ID = 1
        END
        
    IF @WeightTypeID = 0
    BEGIN
		SET @WeightType = '<None>'
    END
    
    IF @WeightType <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
						  LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_AW_Weight (Description, AW_User_Companies_ID) VALUES (@WeightType, @CompanyID)

        			SELECT @WeightTypeID = Scope_Identity()
                END
            ELSE
                BEGIN
                    SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                END
        END


    ---------------------------------------------------------
    --> FIND the ID of the PRODUCT if ACTIVE or INSERT NEW
    ---------------------------------------------------------
    SET @ProductID = 0

    SELECT @ProductID = AP_Products_ID
    FROM AP_Products p
    INNER JOIN Lup_AP_Product_Manufacturers m
    On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
    WHERE Product_Code = @ProductCode
      --AND CONVERT(CHAR(19), Date_Captured) = CONVERT(CHAR(19), @DateCaptured)
      AND m.Description = @Manuf
      AND p.Slu_AW_Active_ID = 1

    IF @ProductID IS NULL
        BEGIN
            SET @ProductID = 0
        END
    ---------------------------------------------------------


    IF @chkUpdProtector = 1
        BEGIN
            IF @ProductID > 0
                BEGIN
                    UPDATE AP_Products
                    SET Description = @Description,
                        --Date_Captured = @DateCaptured, --RL V6.0
                        SKU_Code = @SKUCode,
                        Alternate_Code1 = @AltCode1,
                        Alternate_Code2 = @BarCode,
                        Lup_AP_Product_Manufacturers_ID = @ManufID,
                        Manufacturer_Code = @ManufCode,
                        Manufacturer_Description = @ManufDesc,
                        Default_Supplier_ID = @SupplierID,
                        Lup_AP_Product_Types_ID = @TypeID,
                        Lup_AP_Product_Groups_ID = @GroupID,
                        Lup_AP_Product_Departments_ID = @DeptID,
                        Lup_AP_Product_Locations_ID = @LocationID,
                        Lup_AP_Purchase_Categories_ID = @PurchaseCatID,
                        Standard_Cost = Cast(@StdCost As Money),
                        Price1_Effective_Date = @Price1Date,
                        Price1_Price1 = Cast(@Price11 As Money),
                        Price1_Price2 = Cast(@Price12 As Money),
                        Price2_Effective_Date = @Price2Date,
                        Price2_Price1 = Cast(@Price21 As Money),
                        Price2_Price2 = Cast(@Price22 As Money),
                        Pack_Volume = @PackVolume,
                        Pack_Mass = @PackMass,
                        Slu_AW_Active_ID = @ActiveID,
                        Slu_AW_YesNo_Edit_Price = @EditPriceID,
                        Slu_AW_YesNo_Edit_Discount = @EditDiscID,
                        Max_Discount_Perc = @MinGP,
                        Slu_AW_YesNo_Max_Discount_Perc = @ApplyMinID,
                        
                        Levy_AP_Product_ID = @LevyID,
                        Lup_AP_AW_Weight_ID = @WeightTypeID,
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @RetCode = 1
                END
            ELSE
                BEGIN
                    INSERT AP_Products
                        (
                            Description,
                            Print_Description,
                            Product_Code,
                            Pack_Size,
                            Date_Captured,
                            SKU_Code,
                            Alternate_Code1,
                            Alternate_Code2,
                            Lup_AP_Product_Manufacturers_ID,
                            Manufacturer_Code,
                            Manufacturer_Description,
                            Default_Supplier_ID,
                            Lup_AP_Product_Types_ID,
                            Lup_AP_Product_Groups_ID,
                            Lup_AP_Product_Departments_ID,
                            Lup_AP_Product_Locations_ID,
                            Lup_AP_Purchase_Categories_ID,
                            Standard_Cost,
                            Price1_Effective_Date,
                            Price1_Price1,
                            Price1_Price2,
                            Price2_Effective_Date,
                            Price2_Price1,
                            Price2_Price2,
                            Pack_Volume,
                            Pack_Mass,
                            Slu_AW_Active_ID,
                            Slu_AW_YesNo_Edit_Price,
                            Slu_AW_YesNo_Edit_Discount,
                            Max_Discount_Perc,
                            Slu_AW_YesNo_Max_Discount_Perc,                            
                            AW_User_Companies_ID,
                            
							Levy_AP_Product_ID,
						    Lup_AP_AW_Weight_ID,
							Product_Weight,
							[User_ID]  
                        )
                    VALUES
                        (
                            @Description,
                            Left(@Description,30),
                            @ProductCode,
                            @Size,
                            --@DateCaptured,
                            GETDATE(), --RL V6.0
                            @SKUCode,
                            @AltCode1,
                            @BarCode,
                            @ManufID,
                            @ManufCode,
                            @ManufDesc,
                            @SupplierID,
                            @TypeID,
                            @GroupID,
                            @DeptID,
                            @LocationID,
                            @PurchaseCatID,
                            Cast(@StdCost As Money),
                            @Price1Date,
                            Cast(@Price11 As Money),
                            Cast(@Price12 As Money),
                            @Price2Date,
                            Cast(@Price21 As Money),
                            Cast(@Price22 As Money),
                            @PackVolume,
                            @PackMass,
                            @ActiveID,
                            @EditPriceID,
                            @EditDiscID,
                            @MinGP,
                            @ApplyMinID,
                            @CompanyID,
                            
							@LevyID,
						    @WeightTypeID,
							@Weight,
							@UserID                                                    
                        )
        
					SELECT @ProductID = Scope_Identity()        
                    SET @RetCode = 2
                END
        END
    ELSE
        BEGIN
            IF @ProductID > 0
                BEGIN
                    UPDATE AP_Products
                    SET Description = @Description,
                        --Date_Captured = @DateCaptured, --RL V6.0
                        SKU_Code = @SKUCode,
                        Alternate_Code1 = @AltCode1,
                        Alternate_Code2 = @BarCode,
                        Lup_AP_Product_Manufacturers_ID = @ManufID,
                        Manufacturer_Code = @ManufCode,
                        Manufacturer_Description = @ManufDesc,
                        Default_Supplier_ID = @SupplierID,
                        Lup_AP_Product_Types_ID = @TypeID,
                        Lup_AP_Product_Groups_ID = @GroupID,
                        Lup_AP_Product_Departments_ID = @DeptID,
                        Lup_AP_Product_Locations_ID = @LocationID,
                        Lup_AP_Purchase_Categories_ID = @PurchaseCatID,
                        Standard_Cost = Cast(@StdCost As Money),
                        Price1_Effective_Date = @Price1Date,
                        Price1_Price1 = Cast(@Price11 As Money),
                        Price1_Price2 = Cast(@Price12 As Money),
                        Price2_Effective_Date = @Price2Date,
                        Price2_Price1 = Cast(@Price21 As Money),
                        Price2_Price2 = Cast(@Price22 As Money),
                        Pack_Volume = @PackVolume,
                        Pack_Mass = @PackMass,
                        Slu_AW_Active_ID = @ActiveID,

                        Levy_AP_Product_ID = @LevyID,
                        Lup_AP_AW_Weight_ID = @WeightTypeID,
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                                                
                    WHERE AP_Products_ID = @ProductID
        
                    SET @RetCode = 1
                END
            ELSE
                BEGIN
                    INSERT AP_Products
                        (
                            Description,
                            Print_Description,
                            Product_Code,
                            Pack_Size,
                            Date_Captured,
                            SKU_Code,
                            Alternate_Code1,
                            Alternate_Code2,
                            Lup_AP_Product_Manufacturers_ID,
                            Manufacturer_Code,
                            Manufacturer_Description,
                            Default_Supplier_ID,
                            Lup_AP_Product_Types_ID,
                            Lup_AP_Product_Groups_ID,
                            Lup_AP_Product_Departments_ID,
                            Lup_AP_Product_Locations_ID,
                            Lup_AP_Purchase_Categories_ID,
                            Standard_Cost,
                            Price1_Effective_Date,
                            Price1_Price1,
                            Price1_Price2,
                            Price2_Effective_Date,
                            Price2_Price1,
                            Price2_Price2,
                            Pack_Volume,
                            Pack_Mass,
                            Slu_AW_Active_ID,
                            AW_User_Companies_ID,
                            
							Levy_AP_Product_ID,
						    Lup_AP_AW_Weight_ID,
							Product_Weight,
							[User_ID]                     
                        )
                    VALUES
                        (
                            @Description,
                            Left(@Description,30),
                            @ProductCode,
                            @Size,
                            --@DateCaptured,
                            GETDATE(), --RL V6.0
                            @SKUCode,
                            @AltCode1,
                            @BarCode,
                            @ManufID,
                            @ManufCode,
                            @ManufDesc,
                            @SupplierID,
                            @TypeID,
                            @GroupID,
                            @DeptID,
                            @LocationID,
                            @PurchaseCatID,
                            Cast(@StdCost As Money),
                            @Price1Date,
                            Cast(@Price11 As Money),
                            Cast(@Price12 As Money),
                            @Price2Date,
                            Cast(@Price21 As Money),
                            Cast(@Price22 As Money),
                            @PackVolume,
                            @PackMass,
                            @ActiveID,
                            @CompanyID,

							@LevyID,
						    @WeightTypeID,
							@Weight,
							@UserID
                        )
                        
					SELECT @ProductID = Scope_Identity()
                    SET @RetCode = 2
                END
        END
	
	IF (@ProductID <> 0 AND @SupplierID <> 0)
	BEGIN
		IF NOT EXISTS
		(
			SELECT 1
			FROM AP_Products_Suppliers
			WHERE AP_Products_ID = @ProductID
			AND AO_Suppliers_ID = @SupplierID
		)
		BEGIN
			INSERT INTO AP_Products_Suppliers(AP_Products_ID, AO_Suppliers_ID, Start_Date, User_ID)
			VALUES(@ProductID, @SupplierID, GETDATE(), @UserID)
		END	
	END


RETURN @RetCode
GO

--39 Bind_Defaults Left Out For now
--40 AP_Products_Audit
IF EXISTS 
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AP_Products_Audit]') 
    AND OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'AP_Products_Audit_ID'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit
		ADD AP_Products_Audit_ID int NOT NULL IDENTITY(1,1) PRIMARY KEY	
	END		
		
	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'Record_Action'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD Record_Action varchar(50)
	END		
		
	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'Action_Date'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD Action_Date DateTime
	END		

	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'User_ID'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD [User_ID] Int
	END		

	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'AP_Products_ID'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD AP_Products_ID Int
	END		

	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'Field'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD Field Varchar(50)
	END		

	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'Prev_Value'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD Prev_Value Varchar(50)
	END		

	IF NOT EXISTS 
	(
		SELECT * 
		FROM dbo.SYSOBJECTS  
			INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
		WHERE 
			SYSOBJECTS.NAME = 'AP_Products_Audit' 
			AND SYSCOLUMNS.NAME = 'New_Value'		
	)
	BEGIN		
		ALTER TABLE AP_Products_Audit ADD New_Value Varchar(50)
	END		
END
GO

IF NOT EXISTS 
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AP_Products_Audit]') 
    AND OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	CREATE TABLE [dbo].[AP_Products_Audit]
	(
		[AP_Products_Audit_ID] [int] IDENTITY(1,1) NOT NULL,
		[Record_Action] [varchar](50) NULL,
		[Action_Date] [datetime] NULL,
		[User_ID] [int] NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Field] [varchar](50) NULL,
		[Prev_Value] [varchar](50) NULL,
		[New_Value] [varchar](50) NULL
	)
END
GO

IF NOT EXISTS 
(
	SELECT 1 
	FROM sysindexes 
    WHERE name = 'IX_AP_Products_Audit_AP_Products_ID'
) 
CREATE INDEX IX_AP_Products_Audit_AP_Products_ID
   ON AP_Products_Audit (AP_Products_ID) With FILLFACTOR = 80
GO

--41 sp_AP_Products_Audit_Select
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Audit_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Audit_Select]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Products_Audit_Select]    Script Date: 11/14/2013 11:14:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Select
--Purpose       :Return Audit Data on AP_Products
--Date          :2013/10/30
--Authors       :RL
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Select '2013-10-14', '2013-10-29', 0
-- Exec sp_AP_Products_Audit_Select NULL, NULL, NULL
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Select]
	(
        @FromDate	DATETIME,
        @ToDate		DATETIME,
        @Days		INT
	)
AS

SET NOCOUNT ON

--SET @FromDate = '2013-10-01'
--SET @ToDate = '2013-11-03'

	IF @ToDate IS NULL
		SET @ToDate = GetDate()
				
	IF @FromDate IS  NULL
		SET @FromDate = GetDate()

	IF (@FromDate IS NOT NULL AND 
		@ToDate IS NOT NULL)
	BEGIN
		SELECT @FromDate = CAST(Convert(Varchar(10),@FromDate,120) AS DATETIME)
		SELECT @ToDate = CAST(Convert(Varchar(10),DateAdd(dd,1,@ToDate),120) AS DATETIME)		
	END

	IF @Days <> 0
	BEGIN
		SET @FromDate = GetDate()
		SET @ToDate = DateAdd(dd,(@Days*-1),@FromDate)
		
		SELECT @FromDate = CAST(Convert(Varchar(10),@FromDate,120) AS DATETIME)
		SELECT @ToDate = CAST(Convert(Varchar(10),DateAdd(dd,1,@ToDate),120) AS DATETIME)			
	END

SELECT	'1' + '|' + 
		left('Action_Date' + REPLICATE(' ',19), 19) + '|' +
		left('ID' + REPLICATE(' ',7), 7) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +
		left('Product_Description' + REPLICATE(' ',50), 50) + '|' +
		left('Action' + REPLICATE(' ',6), 6) + '|' +
		left('Field' + REPLICATE(' ',20), 20) + '|' +		
		left('Prev_Value'+ REPLICATE(' ',50), 50) + '|' +
		left('New_Value'+ REPLICATE(' ',50), 50)	
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +		
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		left(ynp.[Description] + REPLICATE(' ',50), 50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Field = 'Slu_AW_Active_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Description'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Print_Description'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Product_Code' AND 
	  ap.Record_Action = 'Update'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  	  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
WHERE ap.Field = 'Lup_AP_Product_Departments_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
WHERE ap.Field = 'Lup_AP_Product_Groups_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
WHERE ap.Field = 'Lup_AP_Product_Locations_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
WHERE ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
WHERE ap.Field = 'Lup_AP_Product_Types_ID' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Lup_AP_Purchase_Categories_ID'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate   
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +  --Product Code Stored Here
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	--Product Description Stored Here
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Delete' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price1'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price2'
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate   
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price1,0) As Varchar(50)) + REPLICATE(' ',50), 50)				
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price2,0) As Varchar(50)) + REPLICATE(' ',50), 50)					
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(p.Lup_AP_Purchase_Categories_ID,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID		
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(p.Lup_AP_Product_Types_ID,0) AS INT) = ln.Lup_AP_Product_Types_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(p.Lup_AP_Product_Manufacturers_ID,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(p.Lup_AP_Product_Locations_ID,0) AS INT) = ln.Lup_AP_Product_Locations_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(p.Lup_AP_Product_Groups_ID,0) AS INT) = ln.Lup_AP_Product_Groups_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(p.Lup_AP_Product_Departments_ID,0) AS INT) = ln.Lup_AP_Product_Departments_ID				
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(p.Print_Description,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(p.Slu_AW_Active_ID AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Record_Action = 'Insert' 
AND  CAST(Action_Date AS DATETIME) BETWEEN @FromDate AND @ToDate  
ORDER BY 1

SET NOCOUNT OFF
GO

--42 sp_AP_Products_Audit_Select2
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Audit_Select2]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Audit_Select2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Select2
--Purpose       :Return Audit Data on AP_Products
--Date          :2014/04/11
--Authors       :RL
--Version		:6.0
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Select2 25890, '2013-10-14', '2015-10-29', 0, 0, 0, 0
-- Exec sp_AP_Products_Audit_Select NULL, NULL, NULL
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Select2]
	(
        @AP_Products_ID		INT,
        @FromDate			DATETIME,
        @ToDate				DATETIME,
        @ShowQuantity		BIT,
        @ShowLastSale		BIT,
        @ShowAverageCost	BIT,
        @ShowLastCost		BIT
	)
AS

SET NOCOUNT ON

SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',
	ap.Prev_Value As 'Previous Value',
	ap.New_Value AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Print Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Print_Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'    
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Search Keyword' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Keywords'
	AND	ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Type' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Types_ID' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Department' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID			
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Departments_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Location' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Locations_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Purchase Category' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID				
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Purchase_Categories_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Serial Number' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Serial_Number'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Manufacturer' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(lp.[Description],'') As 'Previous Value',
	ISNULL(ln.[Description],'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Manufacturer Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Manufacturer_Code'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Manufacturer Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID	
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Manufacturer_Description'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Default Supplier' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.Supplier_Name As 'Previous Value',
	ynn.Supplier_Name AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AO_Suppliers ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AO_Suppliers_ID
	INNER JOIN AO_Suppliers ynn
		ON CAST(ap.New_Value AS INT) = ynn.AO_Suppliers_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Default_Supplier_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Self Managed' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Self_Managed'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Active' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_Active_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Product_Code' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'SKU Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'SKU_Code' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Supercession Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Supercession' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Alternate Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Alternate_Code1' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Bar Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Alternate_Code2' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Size' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Size' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Measure' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AP_Units_Of_Measure ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AP_Units_Of_Measure ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AP_Units_Of_Measure_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Packaging' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Strength' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Mass_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Mass_Codes_ID
	INNER JOIN Lup_AP_Mass_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Mass_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Mass_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'   
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Volume' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Volume' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Pack Mass' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Pack_Mass' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_AW_Weight ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_AW_Weight_ID
	INNER JOIN Lup_AP_AW_Weight ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_AW_Weight_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_AW_Weight_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Weight' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Product_Weight' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Qty On Hand' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'On_Hand' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	AND @ShowQuantity = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Last Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Last_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	And @ShowLastCost = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Average Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Average_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND	ap.Record_Action = 'Update'  
	AND @ShowAverageCost = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Standard Cost' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Standard_Cost' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Average Markup' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Average_Markup' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Last Sale Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Last_Sale_Date' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
	AND ap.Record_Action = 'Update'  
	AND @ShowLastSale = 1
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Service Level' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Service_Level' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Max Order Qty' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Max_Order_Qty' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min Order Qty' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Min_Order_Qty' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min Stock Level' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Min_Stock_Level'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price1 Effective Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Effective_Date'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 1_1' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Price1'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 1_2' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price1_Price2'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price2 Effective Date' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Effective_Date'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 2_1' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Price1'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Price 2_2' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Price2_Price2'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Rounding Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Rounding_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Rounding_Codes_ID
	INNER JOIN Lup_AP_Rounding_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Rounding_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Rounding_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Tax Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Sys_AW_Tax_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Sys_AW_Tax_Codes_ID
	INNER JOIN Sys_AW_Tax_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Sys_AW_Tax_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Sys_AW_Tax_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sell By Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Sell_By_Codes_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Sell_By_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Sell_By_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION

--Levy
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	CASE 
	When ISNULL(ynp.[Description],'') = '' Then '<None>'
	ELSE ynp.[Description]		
	END As 'Previous Value',
	CASE 
	When ISNULL(ynn.[Description],'') = '' Then '<None>'
	ELSE ynn.[Description]		
	END As 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AP_Products ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AP_Products_ID
	INNER JOIN AP_Products ynn
		ON CAST(ap.New_Value AS INT) = ynn.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Levy_AP_Product_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sell By Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Sell_By_Codes_ID
	INNER JOIN Lup_AP_Sell_By_Codes ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Sell_By_Codes_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Sell_By_Codes_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Non-Stock Item' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Non_Stock_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Item' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Levy_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Levy Unit Of Measure' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_AW_Weight ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_AW_Weight_ID
	INNER JOIN Lup_AP_AW_Weight ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_AW_Weight_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Levy_Weight_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Sales Discount Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Discount_Groups ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Discount_Groups_ID
	INNER JOIN Lup_AP_Discount_Groups ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Discount_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Discount_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Cost Plus' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Cost_Plus_Item'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate 
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Cost Plus Group' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Lup_AP_Markup_Groups ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Lup_AP_Markup_Groups_ID
	INNER JOIN Lup_AP_Markup_Groups ynn
		ON CAST(ap.New_Value AS INT) = ynn.Lup_AP_Markup_Groups_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Lup_AP_Markup_Groups_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Edit Price' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Edit_Price'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Edit Discount' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Edit_Discount'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Min GP' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ISNULL(ap.Prev_Value,'') As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'		
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Max_Discount_Perc'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Enforce Min GP' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_YesNo ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_YesNo_ID
	INNER JOIN Slu_AW_YesNo ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_YesNo_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'Slu_AW_YesNo_Max_Discount_Perc'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL Purchase Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_Purchases_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL Sales Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_Sales_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'GL COS Account' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	ynp.[Description] As 'Previous Value',
	ynn.[Description] AS 'New Value'
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN AB_Accounts ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.AB_Accounts_ID
	INNER JOIN AB_Accounts ynn
		ON CAST(ap.New_Value AS INT) = ynn.AB_Accounts_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Field = 'GL_COS_ID'
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate
	AND	ap.Record_Action = 'Update'
UNION

--Insert
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.Prev_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Insert' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Insert' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
--Delete
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Code' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.Prev_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Delete' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
UNION
SELECT	
	ap.Action_Date AS 'Action Date',
	ap.Record_Action AS 'Action',
	ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
	'Product Description' AS 'Field',
--	ISNULL(p.Product_Code,'') AS 'Product Code',
--	ISNULL(p.[Description],'') As 'Product Description',	
	'' As 'Previous Value',
	ISNULL(ap.New_Value,'') AS 'New Value'	
FROM AP_Products_Audit ap
--	LEFT OUTER JOIN AP_Products p
--		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN AW_Users u
		ON ap.[User_ID] = u.AW_Users_ID		
WHERE ap.AP_Products_ID = @AP_Products_ID
	AND ap.Record_Action = 'Delete' 
	AND ap.Action_Date BETWEEN @FromDate AND @ToDate  
ORDER BY 1, 2

SET NOCOUNT OFF
GO

--43 sp_AP_Products_Audit_Temp_Select
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Audit_Temp_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Audit_Temp_Select]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Products_Audit_Temp_Select]    Script Date: 11/14/2013 11:14:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Audit_Temp_Select
--Purpose       :Return Audit Data on AP_Products - Runs via Task Scheduler
--Date          :2013/10/30
--NOTES			:ALL CHANGES DONE IN THIS PROC SHOULD BE DONE IN 
--				:sp_AP_Products_Audit_Temp_Select as well
--Authors       :RL
-------------------------------------------------------------------------------
--16923
--986
-- Exec sp_AP_Products_Audit_Temp_Select
-- Exec sp_AP_Products_Audit_Temp_Select
-- AA3_Silverlakes
CREATE PROCEDURE [dbo].[sp_AP_Products_Audit_Temp_Select]
AS

SET NOCOUNT ON

--Update AP_Products_Audit
--Set Changes_Sent = 0

--TRUNCATE TABLE AP_Products_Audit_Temp

--INSERT INTO AP_Products_Audit_Temp
--SELECT *
--FROM AP_Products_Audit
--WHERE ISNULL(Changes_Sent,0) = 0

--UPDATE AP_Products_Audit
--SET Changes_Sent = 1
--WHERE ISNULL(Changes_Sent,0) = 0

SELECT	'1' + '|' + 
		left('Action_Date' + REPLICATE(' ',19), 19) + '|' +
		left('ID' + REPLICATE(' ',7), 7) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +
		left('Product_Description' + REPLICATE(' ',50), 50) + '|' +
		left('Action' + REPLICATE(' ',6), 6) + '|' +
		left('Field' + REPLICATE(' ',20), 20) + '|' +		
		left('Prev_Value'+ REPLICATE(' ',50), 50) + '|' +
		left('New_Value'+ REPLICATE(' ',50), 50)	
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +		
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		left(ynp.[Description] + REPLICATE(' ',50), 50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynp
		ON CAST(ap.Prev_Value AS INT) = ynp.Slu_AW_Active_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(ap.New_Value AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Field = 'Slu_AW_Active_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Description'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Print_Description'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Code' + REPLICATE(' ',20), 20) + '|' +		
		left(ap.Prev_Value + REPLICATE(' ',50), 50) + '|' +
		left(ap.New_Value + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Field = 'Product_Code' AND 
	  ap.Record_Action = 'Update'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Departments_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Departments_ID
WHERE ap.Field = 'Lup_AP_Product_Departments_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Groups_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Groups_ID
WHERE ap.Field = 'Lup_AP_Product_Groups_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Locations_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Locations_ID
WHERE ap.Field = 'Lup_AP_Product_Locations_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Manufacturers_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID
WHERE ap.Field = 'Lup_AP_Product_Manufacturers_ID' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Product_Types_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Product_Types_ID
WHERE ap.Field = 'Lup_AP_Product_Types_ID' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(lp.[Description],'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Lup_AP_Purchase_Categories_ID'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +  --Product Code Stored Here
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	--Product Description Stored Here
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Delete' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price1'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(p.Product_Code,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(p.Description,'') + REPLICATE(' ',50), 50) + '|' +				
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',50), 50) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories lp
		ON CAST(ISNULL(ap.Prev_Value,0) AS INT) = lp.Lup_AP_Purchase_Categories_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(ap.New_Value,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID
WHERE ap.Field = 'Price1_Price2'
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +
		left('' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		REPLICATE(' ',50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price1' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price1,0) As Varchar(50)) + REPLICATE(' ',50), 50)						
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Price1_Price2' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(Cast(ISNULL(p.Price1_Price2,0) As Varchar(50)) + REPLICATE(' ',50), 50)						
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Purchase_Cat' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Purchase_Categories ln
		ON CAST(ISNULL(p.Lup_AP_Purchase_Categories_ID,0) AS INT) = ln.Lup_AP_Purchase_Categories_ID		
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Types' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Types ln
		ON CAST(ISNULL(p.Lup_AP_Product_Types_ID,0) AS INT) = ln.Lup_AP_Product_Types_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Manuf' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Manufacturers ln
		ON CAST(ISNULL(p.Lup_AP_Product_Manufacturers_ID,0) AS INT) = ln.Lup_AP_Product_Manufacturers_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Locations' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Locations ln
		ON CAST(ISNULL(p.Lup_AP_Product_Locations_ID,0) AS INT) = ln.Lup_AP_Product_Locations_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Groups' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Groups ln
		ON CAST(ISNULL(p.Lup_AP_Product_Groups_ID,0) AS INT) = ln.Lup_AP_Product_Groups_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Product_Departments' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(ln.[Description],'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	LEFT OUTER JOIN Lup_AP_Product_Departments ln
		ON CAST(ISNULL(p.Lup_AP_Product_Departments_ID,0) AS INT) = ln.Lup_AP_Product_Departments_ID				
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Print_Description' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ISNULL(p.Print_Description,'') + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
WHERE ap.Record_Action = 'Insert' 
UNION
SELECT	
		Convert(Varchar(1),2) + '|' +
		left(Convert(Varchar(20),ap.Action_Date,120) + REPLICATE(' ',19), 19) + '|' +
		left(Convert(Varchar(10),ap.AP_Products_ID) + REPLICATE(' ',7), 7) + '|' +
		left(ISNULL(ap.Prev_Value,'') + REPLICATE(' ',20), 20) + '|' +
		left(ISNULL(ap.New_Value,'') + REPLICATE(' ',50), 50) + '|' +	
		left(ap.Record_Action + REPLICATE(' ',6), 6) + '|' +	
		left('Active' + REPLICATE(' ',20), 20) + '|' +		
		REPLICATE(' ',50) + '|' +
		left(ynn.[Description] + REPLICATE(' ',50), 50)	
FROM AP_Products_Audit_Temp ap
	LEFT OUTER JOIN AP_Products p
		ON ap.AP_Products_ID = p.AP_Products_ID
	INNER JOIN Slu_AW_Active ynn
		ON CAST(p.Slu_AW_Active_ID AS INT) = ynn.Slu_AW_Active_ID
WHERE ap.Record_Action = 'Insert' 
ORDER BY 1

SET NOCOUNT OFF
GO

--44 trg_AP_Products_DEL
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AP_Products_DEL' 
    AND type = 'TR'
)
DROP TRIGGER trg_AP_Products_DEL
GO
CREATE TRIGGER [dbo].[trg_AP_Products_DEL] ON [dbo].[AP_Products]
FOR DELETE 
AS
BEGIN
	INSERT INTO AP_Products_Audit
	(
		Record_Action, 
		Action_Date, 
		[User_ID],
		AP_Products_ID, 
		Field, 
		Prev_Value, 
		New_Value
	)
	SELECT
		'Delete', 
		GetDate(), 
		1,
		AP_Products_ID, 
		'', 
		IsNull(Product_Code,''),
		IsNull(Description,'')
    FROM Deleted     
END
GO

--45 trg_AP_Products_INS
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AP_Products_INS' 
    AND type = 'TR'
)
DROP TRIGGER trg_AP_Products_INS
GO
CREATE TRIGGER [dbo].[trg_AP_Products_INS] ON [dbo].[AP_Products]
FOR INSERT 
AS
BEGIN

	INSERT INTO AP_Products_Audit
	(
		Record_Action, 
		Action_Date, 
		[User_ID],		
		AP_Products_ID, 
		Field, 
		Prev_Value, 
		New_Value
	)
	SELECT
		'Insert', 
		GetDate(), 
		[User_ID],		
		AP_Products_ID, 
		'', 
		IsNull(Product_Code,''),
		IsNull(Description,'')
    FROM Inserted     
     
END
GO

--46 trg_AP_Products_UPD
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AP_Products_UPD' 
    AND type = 'TR'
)
DROP TRIGGER trg_AP_Products_UPD
GO

CREATE TRIGGER [dbo].[trg_AP_Products_UPD] ON [dbo].[AP_Products]
AFTER UPDATE 
AS
BEGIN

	DECLARE @AP_Products_ID	int,	
	
	--Deleted Data
	@d_Description varchar(50),
	@d_Print_Description varchar(30),
	@d_Product_Code varchar(20),
	@d_SKU_Code varchar(20),
	@d_Pack_Size decimal(9,3),
	@d_Measure decimal(9,3),
	@d_Slu_AP_Units_Of_Measure_ID int,
	@d_Manufacturer_Code varchar(20),
	@d_Manufacturer_Description varchar(50),
	@d_Slu_AW_YesNo_Self_Managed int,
	@d_Lup_AP_Product_Manufacturers_ID int,
	@d_Default_Supplier_ID int,
	@d_Lup_AP_Product_Types_ID int,
	@d_Lup_AP_Product_Groups_ID int,
	@d_Lup_AP_Product_Departments_ID int,
	@d_Lup_AP_Product_Locations_ID int,
	@d_Lup_AP_Sell_By_Codes_ID int,
	@d_Alternate_Code1 varchar(20),
	@d_Alternate_Code2 varchar(20),
	@d_Supercession varchar(20),
	@d_Last_Cost money,
	@d_Average_Cost money,
	@d_Standard_Cost money,
	@d_Standard_Disc1 decimal(7,2),
	@d_Standard_Disc2 decimal(7,2),
	@d_Average_Markup decimal(8,4),
	@d_Price1_Effective_Date datetime,
	@d_Price1_Price1 money,
	@d_Price1_Price2 money,
	@d_Price2_Effective_Date datetime,
	@d_Price2_Price1 money,
	@d_Price2_Price2 money,
	@d_Lup_AP_Rounding_Codes_ID int,
	@d_Sys_AW_Tax_Codes_ID int,
	@d_Lup_AP_Discount_Groups_ID Int,
	@d_Lup_AP_Commission_Groups_ID Int,
	@d_Pack_Volume decimal(9,3),
	@d_Lup_AP_Mass_Codes_ID int,
	@d_Pack_Mass decimal(9,3),
	@d_Strength varchar(30),
	@d_On_Hand decimal(9,3),
	@d_Sales_Order_Reserved decimal(9,3),
	@d_Quote_Reserved decimal(9,3),
	@d_Job_Reserved decimal(9,3),
	@d_Min_Stock_Level decimal(9,3),
	@d_Last_Sale_Date datetime,
	@d_Service_Level decimal(9,3),
	@d_Max_Order_Qty decimal(9,3),
	@d_Min_Order_Qty decimal(9,3),
	@d_Serial_Number varchar(30),
	@d_Slu_AW_YesNo_Edit_Price Int,
	@d_Slu_AW_YesNo_Edit_Discount Int,
	@d_Max_Discount_Perc decimal(5,2),
	@d_Slu_AW_YesNo_Max_Discount_Perc Int,
	@d_Keywords varchar(50),
	@d_Slu_AW_YesNo_Non_Stock_Item Int,
	@d_GL_Purchases_ID int,
	@d_GL_Sales_ID int,
	@d_GL_COS_ID int,
	@d_Lup_AP_Purchase_Categories_ID int,
	@d_Lup_AP_Markup_Groups_ID Int,
	@d_Slu_AW_YesNo_Cost_Plus_Item Int,
	@d_Date_Captured datetime,
	@d_User_ID int,
	@d_AW_User_Companies_ID int,
	@d_Slu_AW_Active_ID Int,
	@d_Lup_AP_AW_Weight_ID int,
	@d_Product_Weight decimal(9,3),
	@d_Slu_AW_YesNo_Levy_Item Int,
	@d_Levy_AP_Product_ID int,
	@d_Levy_Weight_ID int,
	@d_Slu_AW_YesNo_Sell_Below_Cost int,
	
	--Inserted Data	
	@i_Description varchar(50),
	@i_Print_Description varchar(30),
	@i_Product_Code varchar(20),
	@i_SKU_Code varchar(20),
	@i_Pack_Size decimal(9,3),
	@i_Measure decimal(9,3),
	@i_Slu_AP_Units_Of_Measure_ID int,
	@i_Manufacturer_Code varchar(20),
	@i_Manufacturer_Description varchar(50),
	@i_Slu_AW_YesNo_Self_Managed Int,
	@i_Lup_AP_Product_Manufacturers_ID int,
	@i_Default_Supplier_ID int,
	@i_Lup_AP_Product_Types_ID int,
	@i_Lup_AP_Product_Groups_ID Int,
	@i_Lup_AP_Product_Departments_ID int,
	@i_Lup_AP_Product_Locations_ID int,
	@i_Lup_AP_Sell_By_Codes_ID int,
	@i_Alternate_Code1 varchar(20),
	@i_Alternate_Code2 varchar(20),
	@i_Supercession varchar(20),
	@i_Last_Cost money,
	@i_Average_Cost money,
	@i_Standard_Cost money,
	@i_Standard_Disc1 decimal(7,2),
	@i_Standard_Disc2 decimal(7,2),
	@i_Average_Markup decimal(8,4),
	@i_Price1_Effective_Date datetime,
	@i_Price1_Price1 money,
	@i_Price1_Price2 money,
	@i_Price2_Effective_Date datetime,
	@i_Price2_Price1 money,
	@i_Price2_Price2 money,
	@i_Lup_AP_Rounding_Codes_ID int,
	@i_Sys_AW_Tax_Codes_ID Int,
	@i_Lup_AP_Discount_Groups_ID Int,
	@i_Lup_AP_Commission_Groups_ID Int,
	@i_Pack_Volume decimal(9,3),
	@i_Lup_AP_Mass_Codes_ID int,
	@i_Pack_Mass decimal(9,3),
	@i_Strength varchar(30),
	@i_On_Hand decimal(9,3),
	@i_Sales_Order_Reserved decimal(9,3),
	@i_Quote_Reserved decimal(9,3),
	@i_Job_Reserved decimal(9,3),
	@i_Min_Stock_Level decimal(9,3),
	@i_Last_Sale_Date datetime,
	@i_Service_Level decimal(9,3),
	@i_Max_Order_Qty decimal(9,3),
	@i_Min_Order_Qty decimal(9,3),
	@i_Serial_Number varchar(30),
	@i_Slu_AW_YesNo_Edit_Price Int,
	@i_Slu_AW_YesNo_Edit_Discount Int,
	@i_Max_Discount_Perc decimal(5,2),
	@i_Slu_AW_YesNo_Max_Discount_Perc Int,
	@i_Keywords varchar(50),
	@i_Slu_AW_YesNo_Non_Stock_Item Int,
	@i_GL_Purchases_ID int,
	@i_GL_Sales_ID int,
	@i_GL_COS_ID int,
	@i_Lup_AP_Purchase_Categories_ID int,
	@i_Lup_AP_Markup_Groups_ID Int,
	@i_Slu_AW_YesNo_Cost_Plus_Item Int,
	@i_Date_Captured datetime,
	@i_User_ID int,
	@i_AW_User_Companies_ID int,
	@i_Slu_AW_Active_ID Int,
	@i_Lup_AP_AW_Weight_ID int,
	@i_Product_Weight decimal(9,3),
	@i_Slu_AW_YesNo_Levy_Item Int,
	@i_Levy_AP_Product_ID int,
	@i_Levy_Weight_ID int,
	@i_Slu_AW_YesNo_Sell_Below_Cost int
	
	SELECT 
		@AP_Products_ID = AP_Products_ID,
		
		@d_Description = IsNull(Description,''),
		@d_Print_Description = IsNull(Print_Description,''),
		@d_Product_Code = IsNull(Product_Code,''),
		@d_SKU_Code = IsNull(SKU_Code,''),
		@d_Pack_Size = IsNull(Pack_Size,0),
		@d_Measure = IsNull(Measure,0),
		@d_Slu_AP_Units_Of_Measure_ID = IsNull(Slu_AP_Units_Of_Measure_ID,0),
		@d_Manufacturer_Code = IsNull(Manufacturer_Code,''),
		@d_Manufacturer_Description = IsNull(Manufacturer_Description,''),
		@d_Slu_AW_YesNo_Self_Managed = IsNull(Slu_AW_YesNo_Self_Managed,0),
		@d_Lup_AP_Product_Manufacturers_ID = IsNull(Lup_AP_Product_Manufacturers_ID,0),
		@d_Default_Supplier_ID = IsNull(Default_Supplier_ID,0),
		@d_Lup_AP_Product_Types_ID = IsNull(Lup_AP_Product_Types_ID,0),
		@d_Lup_AP_Product_Groups_ID = IsNull(Lup_AP_Product_Groups_ID,0),
		@d_Lup_AP_Product_Departments_ID = IsNull(Lup_AP_Product_Departments_ID,0),
		@d_Lup_AP_Product_Locations_ID = IsNull(Lup_AP_Product_Locations_ID,0),
		@d_Lup_AP_Sell_By_Codes_ID = IsNull(Lup_AP_Sell_By_Codes_ID,0),
		@d_Alternate_Code1 = IsNull(Alternate_Code1,''),
		@d_Alternate_Code2 = IsNull(Alternate_Code2,''),
		@d_Supercession = IsNull(Supercession,''),
		@d_Last_Cost = IsNull(Last_Cost,0),
		@d_Average_Cost = IsNull(Average_Cost,0),
		@d_Standard_Cost = IsNull(Standard_Cost,0),
		@d_Standard_Disc1 = IsNull(Standard_Disc1,0),
		@d_Standard_Disc2 = IsNull(Standard_Disc2,0),
		@d_Average_Markup = IsNull(Average_Markup,0),
		@d_Price1_Effective_Date = IsNull(Price1_Effective_Date,'1999-01-01'),
		@d_Price1_Price1 = IsNull(Price1_Price1,0),
		@d_Price1_Price2 = IsNull(Price1_Price2,0),
		@d_Price2_Effective_Date = IsNull(Price2_Effective_Date,'1999-01-01'),
		@d_Price2_Price1 = IsNull(Price2_Price1,0),
		@d_Price2_Price2 = IsNull(Price2_Price2,0),
		@d_Lup_AP_Rounding_Codes_ID = IsNull(Lup_AP_Rounding_Codes_ID,0),
		@d_Sys_AW_Tax_Codes_ID = IsNull(Sys_AW_Tax_Codes_ID,0),
		@d_Lup_AP_Discount_Groups_ID = IsNull(Lup_AP_Discount_Groups_ID,0),
		@d_Lup_AP_Commission_Groups_ID = IsNull(Lup_AP_Commission_Groups_ID,0),
		@d_Pack_Volume = IsNull(Pack_Volume,0),
		@d_Lup_AP_Mass_Codes_ID = IsNull(Lup_AP_Mass_Codes_ID,0),
		@d_Pack_Mass = IsNull(Pack_Mass,0),
		@d_Strength = IsNull(Strength,''),
		@d_On_Hand = IsNull(On_Hand,0),
		@d_Sales_Order_Reserved = IsNull(Sales_Order_Reserved,0),
		@d_Quote_Reserved = IsNull(Quote_Reserved,0),
		@d_Job_Reserved = IsNull(Job_Reserved,0),
		@d_Min_Stock_Level = IsNull(Min_Stock_Level,0),
		@d_Last_Sale_Date = IsNull(Last_Sale_Date,'1999-01-01'),
		@d_Service_Level = IsNull(Service_Level,0),
		@d_Max_Order_Qty = IsNull(Max_Order_Qty,0),
		@d_Min_Order_Qty = IsNull(Min_Order_Qty,0),
		@d_Serial_Number = IsNull(Serial_Number,''),
		@d_Slu_AW_YesNo_Edit_Price = IsNull(Slu_AW_YesNo_Edit_Price,1),
		@d_Slu_AW_YesNo_Edit_Discount = IsNull(Slu_AW_YesNo_Edit_Discount,1),
		@d_Max_Discount_Perc = IsNull(Max_Discount_Perc,0),
		@d_Slu_AW_YesNo_Max_Discount_Perc = IsNull(Slu_AW_YesNo_Max_Discount_Perc,1),
		@d_Keywords = IsNull(Keywords,''),
		@d_Slu_AW_YesNo_Non_Stock_Item = IsNull(Slu_AW_YesNo_Non_Stock_Item,0),
		@d_GL_Purchases_ID = IsNull(GL_Purchases_ID,0),
		@d_GL_Sales_ID = IsNull(GL_Sales_ID,0),
		@d_GL_COS_ID = IsNull(GL_COS_ID,0),
		@d_Lup_AP_Purchase_Categories_ID = IsNull(Lup_AP_Purchase_Categories_ID,0),
		@d_Lup_AP_Markup_Groups_ID = IsNull(Lup_AP_Markup_Groups_ID,0),
		@d_Slu_AW_YesNo_Cost_Plus_Item = IsNull(Slu_AW_YesNo_Cost_Plus_Item,0),
		@d_Date_Captured = IsNull(Date_Captured,'1999-01-01'),
		@d_User_ID = IsNull(User_ID,0),
		@d_AW_User_Companies_ID = IsNull(AW_User_Companies_ID,0),
		@d_Slu_AW_Active_ID = IsNull(Slu_AW_Active_ID,1),
		@d_Lup_AP_AW_Weight_ID = IsNull(Lup_AP_AW_Weight_ID,0),
		@d_Product_Weight = IsNull(Product_Weight,0),
		@d_Slu_AW_YesNo_Levy_Item = IsNull(Slu_AW_YesNo_Levy_Item,0),
		@d_Levy_AP_Product_ID = IsNull(Levy_AP_Product_ID,0),
		@d_Levy_Weight_ID = IsNull(Levy_Weight_ID,0),
		@d_Slu_AW_YesNo_Sell_Below_Cost = IsNull(Slu_AW_YesNo_Sell_Below_Cost,0)
	FROM DELETED		
	
	SELECT 
		@i_Description = IsNull(Description,''),
		@i_Print_Description = IsNull(Print_Description,''),
		@i_Product_Code = IsNull(Product_Code,''),
		@i_SKU_Code = IsNull(SKU_Code,''),
		@i_Pack_Size = IsNull(Pack_Size,0),
		@i_Measure = IsNull(Measure,0),
		@i_Slu_AP_Units_Of_Measure_ID = IsNull(Slu_AP_Units_Of_Measure_ID,0),
		@i_Manufacturer_Code = IsNull(Manufacturer_Code,''),
		@i_Manufacturer_Description = IsNull(Manufacturer_Description,''),
		@i_Slu_AW_YesNo_Self_Managed = IsNull(Slu_AW_YesNo_Self_Managed,0),
		@i_Lup_AP_Product_Manufacturers_ID = IsNull(Lup_AP_Product_Manufacturers_ID,0),
		@i_Default_Supplier_ID = IsNull(Default_Supplier_ID,0),
		@i_Lup_AP_Product_Types_ID = IsNull(Lup_AP_Product_Types_ID,0),
		@i_Lup_AP_Product_Groups_ID = IsNull(Lup_AP_Product_Groups_ID,0),
		@i_Lup_AP_Product_Departments_ID = IsNull(Lup_AP_Product_Departments_ID,0),
		@i_Lup_AP_Product_Locations_ID = IsNull(Lup_AP_Product_Locations_ID,0),
		@i_Lup_AP_Sell_By_Codes_ID = IsNull(Lup_AP_Sell_By_Codes_ID,0),
		@i_Alternate_Code1 = IsNull(Alternate_Code1,''),
		@i_Alternate_Code2 = IsNull(Alternate_Code2,''),
		@i_Supercession = IsNull(Supercession,''),
		@i_Last_Cost = IsNull(Last_Cost,0),
		@i_Average_Cost = IsNull(Average_Cost,0),
		@i_Standard_Cost = IsNull(Standard_Cost,0),
		@i_Standard_Disc1 = IsNull(Standard_Disc1,0),
		@i_Standard_Disc2 = IsNull(Standard_Disc2,0),
		@i_Average_Markup = IsNull(Average_Markup,0),
		@i_Price1_Effective_Date = IsNull(Price1_Effective_Date,'1999-01-01'),
		@i_Price1_Price1 = IsNull(Price1_Price1,0),
		@i_Price1_Price2 = IsNull(Price1_Price2,0),
		@i_Price2_Effective_Date = IsNull(Price2_Effective_Date,'1999-01-01'),
		@i_Price2_Price1 = IsNull(Price2_Price1,0),
		@i_Price2_Price2 = IsNull(Price2_Price2,0),
		@i_Lup_AP_Rounding_Codes_ID = IsNull(Lup_AP_Rounding_Codes_ID,0),
		@i_Sys_AW_Tax_Codes_ID = IsNull(Sys_AW_Tax_Codes_ID,0),
		@i_Lup_AP_Discount_Groups_ID = IsNull(Lup_AP_Discount_Groups_ID,0),
		@i_Lup_AP_Commission_Groups_ID = IsNull(Lup_AP_Commission_Groups_ID,0),
		@i_Pack_Volume = IsNull(Pack_Volume,0),
		@i_Lup_AP_Mass_Codes_ID = IsNull(Lup_AP_Mass_Codes_ID,0),
		@i_Pack_Mass = IsNull(Pack_Mass,0),
		@i_Strength = IsNull(Strength,''),
		@i_On_Hand = IsNull(On_Hand,0),
		@i_Sales_Order_Reserved = IsNull(Sales_Order_Reserved,0),
		@i_Quote_Reserved = IsNull(Quote_Reserved,0),
		@i_Job_Reserved = IsNull(Job_Reserved,0),
		@i_Min_Stock_Level = IsNull(Min_Stock_Level,0),
		@i_Last_Sale_Date = IsNull(Last_Sale_Date,'1999-01-01'),
		@i_Service_Level = IsNull(Service_Level,0),
		@i_Max_Order_Qty = IsNull(Max_Order_Qty,0),
		@i_Min_Order_Qty = IsNull(Min_Order_Qty,0),
		@i_Serial_Number = IsNull(Serial_Number,''),
		@i_Slu_AW_YesNo_Edit_Price = IsNull(Slu_AW_YesNo_Edit_Price,0),
		@i_Slu_AW_YesNo_Edit_Discount = IsNull(Slu_AW_YesNo_Edit_Discount,0),
		@i_Max_Discount_Perc = IsNull(Max_Discount_Perc,0),
		@i_Slu_AW_YesNo_Max_Discount_Perc = IsNull(Slu_AW_YesNo_Max_Discount_Perc,0),
		@i_Keywords = IsNull(Keywords,''),
		@i_Slu_AW_YesNo_Non_Stock_Item = IsNull(Slu_AW_YesNo_Non_Stock_Item,0),
		@i_GL_Purchases_ID = IsNull(GL_Purchases_ID,0),
		@i_GL_Sales_ID = IsNull(GL_Sales_ID,0),
		@i_GL_COS_ID = IsNull(GL_COS_ID,0),
		@i_Lup_AP_Purchase_Categories_ID = IsNull(Lup_AP_Purchase_Categories_ID,0),
		@i_Lup_AP_Markup_Groups_ID = IsNull(Lup_AP_Markup_Groups_ID,0),
		@i_Slu_AW_YesNo_Cost_Plus_Item = IsNull(Slu_AW_YesNo_Cost_Plus_Item,0),
		@i_Date_Captured = IsNull(Date_Captured,'1999-01-01'),
		@i_User_ID = IsNull(User_ID,0),
		@i_AW_User_Companies_ID = IsNull(AW_User_Companies_ID,0),
		@i_Slu_AW_Active_ID = IsNull(Slu_AW_Active_ID,1),
		@i_Lup_AP_AW_Weight_ID = IsNull(Lup_AP_AW_Weight_ID,0),
		@i_Product_Weight = IsNull(Product_Weight,0),
		@i_Slu_AW_YesNo_Levy_Item = IsNull(Slu_AW_YesNo_Levy_Item,0),
		@i_Levy_AP_Product_ID = IsNull(Levy_AP_Product_ID,0),
		@i_Levy_Weight_ID = IsNull(Levy_Weight_ID,0),
		@i_Slu_AW_YesNo_Sell_Below_Cost = IsNull(Slu_AW_YesNo_Sell_Below_Cost,0)		
	FROM INSERTED		
	
	IF @d_Description <> @i_Description
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Description', @d_Description, @i_Description)
	END	
	IF @d_Print_Description <> @i_Print_Description
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Print_Description', @d_Print_Description, @i_Print_Description)
	END	
	IF @d_Product_Code <> @i_Product_Code
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Product_Code', @d_Product_Code, @i_Product_Code)
	END	
	IF @d_SKU_Code <> @i_SKU_Code
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'SKU_Code', @d_SKU_Code, @i_SKU_Code)
	END	
	IF @d_Pack_Size <> @i_Pack_Size
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Pack_Size', Convert(Varchar(50),@d_Pack_Size), Convert(Varchar(50),@i_Pack_Size))
	END	
	IF @d_Measure <> @i_Measure
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Measure', Convert(Varchar(50),@d_Measure), Convert(Varchar(50),@i_Measure))
	END	
	IF @d_Slu_AP_Units_Of_Measure_ID <> @i_Slu_AP_Units_Of_Measure_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AP_Units_Of_Measure_ID', @d_Slu_AP_Units_Of_Measure_ID, @i_Slu_AP_Units_Of_Measure_ID)
	END	
	IF @d_Manufacturer_Code <> @i_Manufacturer_Code
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Manufacturer_Code', @d_Manufacturer_Code, @i_Manufacturer_Code)
	END	
	IF @d_Manufacturer_Description <> @i_Manufacturer_Description
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Manufacturer_Description', @d_Manufacturer_Description, @i_Manufacturer_Description)
	END	
	IF @d_Slu_AW_YesNo_Self_Managed <> @i_Slu_AW_YesNo_Self_Managed
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Self_Managed', @d_Slu_AW_YesNo_Self_Managed, @i_Slu_AW_YesNo_Self_Managed)
	END	
	IF @d_Lup_AP_Product_Manufacturers_ID <> @i_Lup_AP_Product_Manufacturers_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Product_Manufacturers_ID', @d_Lup_AP_Product_Manufacturers_ID, @i_Lup_AP_Product_Manufacturers_ID)
	END	
	IF @d_Default_Supplier_ID <> @i_Default_Supplier_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Default_Supplier_ID', @d_Default_Supplier_ID, @i_Default_Supplier_ID)
	END	
	IF @d_Lup_AP_Product_Types_ID <> @i_Lup_AP_Product_Types_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Product_Types_ID', @d_Lup_AP_Product_Types_ID, @i_Lup_AP_Product_Types_ID)
	END	
	IF @d_Lup_AP_Product_Groups_ID <> @i_Lup_AP_Product_Groups_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Product_Groups_ID', @d_Lup_AP_Product_Groups_ID, @i_Lup_AP_Product_Groups_ID)
	END	
	IF @d_Lup_AP_Product_Departments_ID <> @i_Lup_AP_Product_Departments_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Product_Departments_ID', @d_Lup_AP_Product_Departments_ID, @i_Lup_AP_Product_Departments_ID)
	END	
	IF @d_Lup_AP_Product_Locations_ID <> @i_Lup_AP_Product_Locations_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Product_Locations_ID', @d_Lup_AP_Product_Locations_ID, @i_Lup_AP_Product_Locations_ID)
	END	
	IF @d_Lup_AP_Sell_By_Codes_ID <> @i_Lup_AP_Sell_By_Codes_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Sell_By_Codes_ID', @d_Lup_AP_Sell_By_Codes_ID, @i_Lup_AP_Sell_By_Codes_ID)
	END	
	IF @d_Alternate_Code1 <> @i_Alternate_Code1
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Alternate_Code1', @d_Alternate_Code1, @i_Alternate_Code1)
	END	
	IF @d_Alternate_Code2 <> @i_Alternate_Code2
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Alternate_Code2', @d_Alternate_Code2, @i_Alternate_Code2)
	END	
	IF @d_Supercession <> @i_Supercession
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Supercession', @d_Supercession, @i_Supercession)
	END	
	IF @d_Last_Cost <> @i_Last_Cost
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Last_Cost', Convert(Varchar(50),@d_Last_Cost), Convert(Varchar(50),@i_Last_Cost))
	END	
	IF @d_Average_Cost <> @i_Average_Cost
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Average_Cost', Convert(Varchar(50),@d_Average_Cost), Convert(Varchar(50),@i_Average_Cost))
	END	
	IF @d_Standard_Cost <> @i_Standard_Cost
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Standard_Cost', Convert(Varchar(50),@d_Standard_Cost), Convert(Varchar(50),@i_Standard_Cost))
	END	
	IF @d_Standard_Disc1 <> @i_Standard_Disc1
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Standard_Disc1', @d_Standard_Disc1, @i_Standard_Disc1)
	END	
	IF @d_Standard_Disc2 <> @i_Standard_Disc2
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Standard_Disc2', @d_Standard_Disc2, @i_Standard_Disc2)
	END	
	IF @d_Average_Markup <> @i_Average_Markup
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Average_Markup', @d_Average_Markup, @i_Average_Markup)
	END	
	IF @d_Price1_Effective_Date <> @i_Price1_Effective_Date
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price1_Effective_Date', CONVERT(Varchar(30),@d_Price1_Effective_Date,121), CONVERT(Varchar(30),@i_Price1_Effective_Date,121))
	END	
	IF @d_Price1_Price1 <> @i_Price1_Price1
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price1_Price1', Convert(Varchar(50),@d_Price1_Price1), Convert(Varchar(50),@i_Price1_Price1))
	END	
	IF @d_Price1_Price2 <> @i_Price1_Price2
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price1_Price2', Convert(Varchar(50),@d_Price1_Price2), Convert(Varchar(50),@i_Price1_Price2))
	END	
	IF @d_Price2_Effective_Date <> @i_Price2_Effective_Date
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price2_Effective_Date', CONVERT(Varchar(30),@d_Price2_Effective_Date,121), CONVERT(Varchar(30),@i_Price2_Effective_Date,121))
	END	
	IF @d_Price2_Price1 <> @i_Price2_Price1
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price2_Price1', Convert(Varchar(50),@d_Price2_Price1), Convert(Varchar(50),@i_Price2_Price1))
	END	
	IF @d_Price2_Price2 <> @i_Price2_Price2
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Price2_Price2', Convert(Varchar(50),@d_Price2_Price2), Convert(Varchar(50),@i_Price2_Price2))
	END	
	IF @d_Lup_AP_Rounding_Codes_ID <> @i_Lup_AP_Rounding_Codes_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Rounding_Codes_ID', @d_Lup_AP_Rounding_Codes_ID, @i_Lup_AP_Rounding_Codes_ID)
	END	
	IF @d_Sys_AW_Tax_Codes_ID <> @i_Sys_AW_Tax_Codes_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Sys_AW_Tax_Codes_ID', @d_Sys_AW_Tax_Codes_ID, @i_Sys_AW_Tax_Codes_ID)
	END	
	IF @d_Lup_AP_Discount_Groups_ID <> @i_Lup_AP_Discount_Groups_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Discount_Groups_ID', @d_Lup_AP_Discount_Groups_ID, @i_Lup_AP_Discount_Groups_ID)
	END	
	IF @d_Lup_AP_Commission_Groups_ID <> @i_Lup_AP_Commission_Groups_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Commission_Groups_ID', @d_Lup_AP_Commission_Groups_ID, @i_Lup_AP_Commission_Groups_ID)
	END	
	IF @d_Pack_Volume <> @i_Pack_Volume
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Pack_Volume', @d_Pack_Volume, @i_Pack_Volume)
	END	
	IF @d_Lup_AP_Mass_Codes_ID <> @i_Lup_AP_Mass_Codes_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Mass_Codes_ID', @d_Lup_AP_Mass_Codes_ID, @i_Lup_AP_Mass_Codes_ID)
	END	
	IF @d_Pack_Mass <> @i_Pack_Mass
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Pack_Mass', @d_Pack_Mass, @i_Pack_Mass)
	END	
	IF @d_Strength <> @i_Strength
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Strength', @d_Strength, @i_Strength)
	END	
	IF @d_On_Hand <> @i_On_Hand
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'On_Hand', @d_On_Hand, @i_On_Hand)
	END	
--	IF @d_Sales_Order_Reserved <> @i_Sales_Order_Reserved
--	BEGIN
--		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, AP_Products_ID, Field, Prev_Value, New_Value)
--		VALUES('Update', GetDate(), @AP_Products_ID, 'Sales_Order_Reserved', @d_Sales_Order_Reserved, @i_Sales_Order_Reserved)
--	END	
--	IF @d_Quote_Reserved <> @i_Quote_Reserved
--	BEGIN
--		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, AP_Products_ID, Field, Prev_Value, New_Value)
--		VALUES('Update', GetDate(), @AP_Products_ID, 'Quote_Reserved', @d_Quote_Reserved, @i_Quote_Reserved)
--	END	
--	IF @d_Job_Reserved <> @i_Job_Reserved
--	BEGIN
--		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, AP_Products_ID, Field, Prev_Value, New_Value)
--		VALUES('Update', GetDate(), @AP_Products_ID, 'Job_Reserved', @d_Job_Reserved, @i_Job_Reserved)
--	END	
	IF @d_Min_Stock_Level <> @i_Min_Stock_Level
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Min_Stock_Level', @d_Min_Stock_Level, @i_Min_Stock_Level)
	END	
	IF @d_Last_Sale_Date <> @i_Last_Sale_Date
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Last_Sale_Date', CONVERT(Varchar(30),@d_Last_Sale_Date,121), CONVERT(Varchar(30),@i_Last_Sale_Date,121))
	END	
	IF @d_Service_Level <> @i_Service_Level
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Service_Level', @d_Service_Level, @i_Service_Level)
	END	
	IF @d_Max_Order_Qty <> @i_Max_Order_Qty
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Max_Order_Qty', @d_Max_Order_Qty, @i_Max_Order_Qty)
	END	
	IF @d_Min_Order_Qty <> @i_Min_Order_Qty
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Min_Order_Qty', @d_Min_Order_Qty, @i_Min_Order_Qty)
	END	
	IF @d_Serial_Number <> @i_Serial_Number
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Serial_Number', @d_Serial_Number, @i_Serial_Number)
	END	
	IF @d_Slu_AW_YesNo_Edit_Price <> @i_Slu_AW_YesNo_Edit_Price
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Edit_Price', @d_Slu_AW_YesNo_Edit_Price, @i_Slu_AW_YesNo_Edit_Price)
	END	
	IF @d_Slu_AW_YesNo_Edit_Discount <> @i_Slu_AW_YesNo_Edit_Discount
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Edit_Discount', @d_Slu_AW_YesNo_Edit_Discount, @i_Slu_AW_YesNo_Edit_Discount)
	END	
	IF @d_Max_Discount_Perc <> @i_Max_Discount_Perc
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Max_Discount_Perc', @d_Max_Discount_Perc, @i_Max_Discount_Perc)
	END	
	IF @d_Slu_AW_YesNo_Max_Discount_Perc <> @i_Slu_AW_YesNo_Max_Discount_Perc
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Max_Discount_Perc', @d_Slu_AW_YesNo_Max_Discount_Perc, @i_Slu_AW_YesNo_Max_Discount_Perc)
	END	
	IF @d_Keywords <> @i_Keywords
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Keywords', @d_Keywords, @i_Keywords)
	END	
	IF @d_Slu_AW_YesNo_Non_Stock_Item <> @i_Slu_AW_YesNo_Non_Stock_Item
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Non_Stock_Item', @d_Slu_AW_YesNo_Non_Stock_Item, @i_Slu_AW_YesNo_Non_Stock_Item)
	END	
	IF @d_GL_Purchases_ID <> @i_GL_Purchases_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'GL_Purchases_ID', @d_GL_Purchases_ID, @i_GL_Purchases_ID)
	END	
	IF @d_GL_Sales_ID <> @i_GL_Sales_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'GL_Sales_ID', @d_GL_Sales_ID, @i_GL_Sales_ID)
	END	
	IF @d_GL_COS_ID <> @i_GL_COS_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'GL_COS_ID', @d_GL_COS_ID, @i_GL_COS_ID)
	END	
	IF @d_Lup_AP_Purchase_Categories_ID <> @i_Lup_AP_Purchase_Categories_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Purchase_Categories_ID', @d_Lup_AP_Purchase_Categories_ID, @i_Lup_AP_Purchase_Categories_ID)
	END	
	IF @d_Lup_AP_Markup_Groups_ID <> @i_Lup_AP_Markup_Groups_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_Markup_Groups_ID', @d_Lup_AP_Markup_Groups_ID, @i_Lup_AP_Markup_Groups_ID)
	END	
	IF @d_Slu_AW_YesNo_Cost_Plus_Item <> @i_Slu_AW_YesNo_Cost_Plus_Item
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Cost_Plus_Item', @d_Slu_AW_YesNo_Cost_Plus_Item, @i_Slu_AW_YesNo_Cost_Plus_Item)
	END	
	IF @d_Date_Captured <> @i_Date_Captured
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Date_Captured', CONVERT(Varchar(30),@d_Date_Captured,121), CONVERT(Varchar(30),@i_Date_Captured,121))
	END	
	IF @d_User_ID <> @i_User_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'User_ID', @d_User_ID, @i_User_ID)
	END	
	IF @d_AW_User_Companies_ID <> @i_AW_User_Companies_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'AW_User_Companies_ID', @d_AW_User_Companies_ID, @i_AW_User_Companies_ID)
	END	
	IF @d_Slu_AW_Active_ID <> @i_Slu_AW_Active_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_Active_ID', @d_Slu_AW_Active_ID, @i_Slu_AW_Active_ID)
	END	
	IF @d_Lup_AP_AW_Weight_ID <> @i_Lup_AP_AW_Weight_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Lup_AP_AW_Weight_ID', @d_Lup_AP_AW_Weight_ID, @i_Lup_AP_AW_Weight_ID)
	END	
	IF @d_Product_Weight <> @i_Product_Weight
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Product_Weight', @d_Product_Weight, @i_Product_Weight)
	END	
	IF @d_Slu_AW_YesNo_Levy_Item <> @i_Slu_AW_YesNo_Levy_Item
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Levy_Item', @d_Slu_AW_YesNo_Levy_Item, @i_Slu_AW_YesNo_Levy_Item)
	END	
	IF @d_Levy_AP_Product_ID <> @i_Levy_AP_Product_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Levy_AP_Product_ID', @d_Levy_AP_Product_ID, @i_Levy_AP_Product_ID)
	END	
	IF @d_Levy_Weight_ID <> @i_Levy_Weight_ID
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Levy_Weight_ID', @d_Levy_Weight_ID, @i_Levy_Weight_ID)
	END	
	IF @d_Slu_AW_YesNo_Sell_Below_Cost <> @i_Slu_AW_YesNo_Sell_Below_Cost
	BEGIN
		INSERT INTO AP_Products_Audit(Record_Action, Action_Date, [User_ID], AP_Products_ID, Field, Prev_Value, New_Value)
		VALUES('Update', GetDate(), @i_User_ID, @AP_Products_ID, 'Slu_AW_YesNo_Sell_Below_Cost', @d_Slu_AW_YesNo_Sell_Below_Cost, @i_Slu_AW_YesNo_Sell_Below_Cost)
	END	

END
GO

--47 sp_RPT_AO_Product_Purchases
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AO_Product_Purchases]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AO_Product_Purchases]
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Product_Purchases
--Purpose       :Retrieves Supplier Purchases by Product
--Date          :2005/05/24
--Authors       :TB
--MODS          :10/06/05 - Replaced Discount AMOUNTS with Discount PERCENTAGES
--2004.4.0      :28/08/08 - Changes ORDER BY from [Supplier], [SupplierID], [Product]
--              :                              to [Product], [Supplier], [SupplierID]
--V6.0	RL	2014-05-09	:Added Document date and Supplier search options
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Product_Purchases]
    (
        @Option tinyint,
        @ChkPeriod int,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @ChkAllSuppliers int,
		@SupplierID int              
    )

AS

SET NOCOUNT ON

	DECLARE @StartPeriod varchar(6),
			@EndPeriod varchar(6),
			@sql varchar(7000)

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)

    SET @sql = ' SELECT '

	SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
	SET @sql = @sql + ' p.AP_Products_ID AS [ProductID], '
	SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID], '
	SET @sql = @sql + ' pd.Lup_AP_Product_Departments_ID AS [DeptID], '
	SET @sql = @sql + ' ISNULL(pd.[Description], '''') AS [DeptName], '
	SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier], '
	SET @sql = @sql + ' ISNULL(t.Document_Date, '''') AS [Date], '
	SET @sql = @sql + ' ISNULL(t.Document_Number, '''') AS [Ref No], '
	SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [Type], '
	SET @sql = @sql + ' ISNULL(gl.[Description], '''') AS [GL Account], '

	SET @sql = @sql + ' t.Slu_AW_Months_ID AS [Month], '
	SET @sql = @sql + ' t.Slu_AW_Years_ID AS [Year], '

	SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
	SET @sql = @sql + ' ISNULL(t.AO_GRV_ID, 0) AS [GRV], '
	SET @sql = @sql + ' ISNULL(gd.Qty, 0) AS [Qty], '
	SET @sql = @sql + ' ISNULL(gd.Unit_Price, 0) AS [Unit Price], '

	SET @sql = @sql + ' ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount], '

	SET @sql = @sql + ' ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade], '
	SET @sql = @sql + ' ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate], '
	SET @sql = @sql + ' ISNULL(gd.Other_Discount_Amount, 0) AS [Other], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Trade_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Trade%], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Rebate_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Rebate%], '

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0 '
	SET @sql = @sql + '		THEN ROUND((gd.Other_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2) '
	SET @sql = @sql + '		ELSE 0.00 '
	SET @sql = @sql + '		END AS [Other%], '

	SET @sql = @sql + ' ISNULL(gd.Net_Amount, 0) AS [Sub-Total], '
	SET @sql = @sql + ' ISNULL(gd.Tax_Amount, 0) AS [Tax], '
	SET @sql = @sql + ' ISNULL(gd.Total_Cost, 0) AS [Total], '

	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + '		p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Last_Cost '
	SET @sql = @sql + ' ) as [LastGP%], '
	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + '		p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Average_Cost '
	SET @sql = @sql + ' ) as [AvgGP%], '
	SET @sql = @sql + ' dbo.GetGrossMargin '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		p.Price1_Effective_Date, '
	SET @sql = @sql + '		p.Price1_Price1, '
	SET @sql = @sql + '		p.Price2_Effective_Date, '
	SET @sql = @sql + ' p.Price2_Price1, '
	SET @sql = @sql + '		getdate(), '
	SET @sql = @sql + '		p.Standard_Cost '
	SET @sql = @sql + ' ) as [StdGP%] '

	SET @sql = @sql + ' FROM AO_Transactions t '
	SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
	SET @sql = @sql + '		ON t.AO_Suppliers_ID = s.AO_Suppliers_ID '
	SET @sql = @sql + ' LEFT OUTER 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 AB_Accounts gl '
	SET @sql = @sql + '		ON t.AB_Accounts_ID = gl.AB_Accounts_ID '
	SET @sql = @sql + ' INNER JOIN AO_GRV gh '
	SET @sql = @sql + '		ON t.AO_GRV_ID = gh.AO_GRV_ID '
	SET @sql = @sql + ' INNER JOIN AO_GRV_Details gd '
	SET @sql = @sql + '		On gh.AO_GRV_ID = gd.AO_GRV_ID '
	SET @sql = @sql + ' INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON gd.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + ' INNER JOIN Lup_AP_Product_Departments pd '
	SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '

	SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ''
	
	IF @ChkPeriod = 1        --Accounting Period
	BEGIN
		SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN ' + @StartPeriod + ' AND ' + @EndPeriod + ''
    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 @ChkAllSuppliers = 0        --Single Supplier Account
	BEGIN
		SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ' '
    END      
          
         
--    ORDER BY [Supplier], [SupplierID], [Product], [Date]
	SET @sql = @sql + '     ORDER BY [Product], [Supplier], [ProductID], [Date] '

	EXEC (@sql)

SET NOCOUNT OFF
GO

--48 sp_RPT_AO_Supplier_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AO_Supplier_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AO_Supplier_Products]
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Supplier_Products
--Purpose       :Retrieves Product Purchases by Supplier
--Date          :2008/08/07
--Authors       :TB
--MODS          :
--V6.0	RL	2014-05-09	:Added Document date and Supplier search options
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AO_Supplier_Products]
    (
        @Option tinyint,
        @ChkPeriod int,
        @MonthID tinyint,
    	@YearID int,
        @ToMonthID tinyint,
    	@ToYearID int,
        @CompanyID int,
        @ChkDates int,
        @StartDate datetime,
        @EndDate datetime,
        @ChkAllSuppliers int,
		@SupplierID int              
    )

AS

SET NOCOUNT ON

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

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@ToMonthID, @ToYearID)


	SET @sql = ' SELECT '
	
	SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID],'
	SET @sql = @sql + ' t.AO_Suppliers_ID AS [SupplierID],'
	SET @sql = @sql + ' pd.Lup_AP_Product_Departments_ID AS [DeptID],'
	SET @sql = @sql + ' ISNULL(pd.[Description], '''') AS [DeptName], '
	SET @sql = @sql + ' ISNULL(s.Supplier_Name, '''') AS [Supplier],'
	SET @sql = @sql + ' ISNULL(t.Document_Date, '''') AS [Date],'
	SET @sql = @sql + ' ISNULL(t.Document_Number, '''') AS [Ref No],'
	SET @sql = @sql + ' ISNULL(tt.Type_Code, '''') AS [Type],'
	SET @sql = @sql + ' ISNULL(gl.[Description], '''') AS [GL Account],'

	SET @sql = @sql + ' t.Slu_AW_Months_ID AS [Month],'
	SET @sql = @sql + ' t.Slu_AW_Years_ID AS [Year],'

	SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product],'
	SET @sql = @sql + ' ISNULL(t.AO_GRV_ID, 0) AS [GRV],'
	SET @sql = @sql + ' ISNULL(gd.Qty, 0) AS [Qty],'
	SET @sql = @sql + ' ISNULL(gd.Unit_Price, 0) AS [Unit Price],'

	SET @sql = @sql + ' ISNULL((gd.Unit_Price * gd.Qty), 0) AS [UnitAmount],'

	SET @sql = @sql + ' ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade],'
	SET @sql = @sql + ' ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate],'
	SET @sql = @sql + ' ISNULL(gd.Other_Discount_Amount, 0) AS [Other],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Trade_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Trade%],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Rebate_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Rebate%],'

	SET @sql = @sql + ' CASE WHEN (gd.Unit_Price * gd.Qty) <> 0'
	SET @sql = @sql + '		THEN ROUND((gd.Other_Discount_Amount / (gd.Unit_Price * gd.Qty)) * 100, 2)'
	SET @sql = @sql + '		ELSE 0.00'
	SET @sql = @sql + '		END AS [Other%],'

	SET @sql = @sql + ' ISNULL(gd.Net_Amount, 0) AS [Sub-Total],'
	SET @sql = @sql + ' ISNULL(gd.Tax_Amount, 0) AS [Tax],'
	SET @sql = @sql + ' ISNULL(gd.Total_Cost, 0) AS [Total],'

	SET @sql = @sql + ' dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Last_Cost'
	SET @sql = @sql + '	) as [LastGP%],'
	SET @sql = @sql + ' dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Average_Cost'
	SET @sql = @sql + ' ) as [AvgGP%],'
	SET @sql = @sql + '	dbo.GetGrossMargin'
	SET @sql = @sql + ' ('
	SET @sql = @sql + '		p.Price1_Effective_Date,'
	SET @sql = @sql + '		p.Price1_Price1,'
	SET @sql = @sql + '		p.Price2_Effective_Date,'
	SET @sql = @sql + '		p.Price2_Price1,'
	SET @sql = @sql + '		getdate(),'
	SET @sql = @sql + '		p.Standard_Cost'
	SET @sql = @sql + ' ) as [StdGP%]'

	SET @sql = @sql + ' FROM AO_Transactions t'
	SET @sql = @sql + ' LEFT JOIN AO_Suppliers s'
	SET @sql = @sql + '		ON t.AO_Suppliers_ID = s.AO_Suppliers_ID'
	SET @sql = @sql + '	LEFT OUTER 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 AB_Accounts gl'
	SET @sql = @sql + '		ON t.AB_Accounts_ID = gl.AB_Accounts_ID'
	SET @sql = @sql + ' INNER JOIN AO_GRV gh'
	SET @sql = @sql + '		ON t.AO_GRV_ID = gh.AO_GRV_ID'
	SET @sql = @sql + ' INNER JOIN AO_GRV_Details gd'
	SET @sql = @sql + '		On gh.AO_GRV_ID = gd.AO_GRV_ID'
	SET @sql = @sql + ' INNER JOIN AP_Products p'
	SET @sql = @sql + '		ON gd.AP_Products_ID = p.AP_Products_ID'
	SET @sql = @sql + ' INNER JOIN Lup_AP_Product_Departments pd'
	SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID'

	SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ''

	IF @ChkPeriod = 1        --Accounting Period
	BEGIN
		SET @sql = @sql + ' AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) BETWEEN ' + @StartPeriod + ' AND ' + @EndPeriod + ''
    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 @ChkAllSuppliers = 0        --Single Supplier Account
	BEGIN
		SET @sql = @sql + ' AND t.AO_Suppliers_ID = ' + CONVERT(varchar(10), @SupplierID) + ''
    END      
         
	SET @sql = @sql + ' ORDER BY [Supplier], [Product], [SupplierID], [Date]'

	EXEC (@sql)
--Select @sql
SET NOCOUNT OFF
GO

--49 Sys_AP_Adjustment_Types Godds Returned
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AP_Adjustment_Types
	WHERE Sys_AP_Adjustment_Types_ID = 7
) 
BEGIN

	SET IDENTITY_INSERT Sys_AP_Adjustment_Types ON
	
	INSERT INTO Sys_AP_Adjustment_Types
	(
		Sys_AP_Adjustment_Types_ID,
		Description
	)
	VALUES
	(
		7,
		'Goods Ruturned'
	)

	SET IDENTITY_INSERT Sys_AP_Adjustment_Types OFF
END
GO

--50 sp_AO_Insert_GRV_Return
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Insert_GRV_Return]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Insert_GRV_Return]
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_GRV_Return
--Purpose       :Inserts a Goods Returned Voucher Details
--Functionality :
--Parameters    :
--Date          :2002/02/13
--Authors       :TB
--MODS          :14/08/02 - Fixed converting sign of @Unit_Last_Cost to negative
--              :           causing a positive @NetAmount being created
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--2004.3.8      :30/05/08 - Reworked AVERAGE COST calculation BEFORE negative conversions
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.5      :03/08/09 - Increased @Qty and @Prev_On_Hand from decimal(9,3) to decimal(12,3)
--              :03/08/09 - Added SET @New_Average_Cost = @Prev_Average_Cost to RETAIN
--              :           PREVIOUS Average_Cost if @New_On_Hand = 0. Because @New_Average_Cost
--              :           was then NEVER SET if @New_On_Hand = 0 this could potentially update
--              :           AP_Products with a NULL Average_Cost value
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_GRV_Return]
    (		
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(12,3),
    	@Unit_Last_Cost money,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@Tax_Code_ID int,
    	@TaxAmount Money = 0,
    	@TotalCost Money = 0,
    	@UserID int,
    	@CompanyID int
    )

AS
	
	DECLARE @Prev_On_Hand Decimal(12,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @New_On_Hand Decimal(9,3),
            @COS_Adjust money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @GRNValue money,
            
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
        	@User_Name varchar(40),
        	@AdjustmentType tinyint,
        	@Note varchar(70),
        	@ProductRef varchar(30),
        	@ProdCode varchar(20)

    BEGIN

        SET @GRNValue = ISNULL(@Qty, 0) * ISNULL(@Unit_Last_Cost, 0)

        ------------------------------------------------------------------------
        --> NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
        ------------------------------------------------------------------------
    	SELECT @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
               @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
      		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
        	   @ProdCode = ISNULL(Product_Code, '')
    	FROM AP_Products
    	WHERE AP_Products_ID = @AP_Products_ID

		SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @AP_Products_ID) + ')'

        SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
        SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

        SET @New_LastCostTotal = @Prev_LastCostTotal - @GRNValue
        SET @New_AvgCostTotal = @Prev_AvgCostTotal - @GRNValue


        SET @New_On_Hand = @Prev_On_Hand - @Qty

        IF @New_On_Hand <> 0
            BEGIN
                -- Calculate NEW Average_Cost
                SET @New_Average_Cost = ROUND((@New_AvgCostTotal / @New_On_Hand), 2)
            END
        ELSE
            BEGIN
                -- Retain OLD Average_Cost
                SET @New_Average_Cost = @Prev_Average_Cost
            END
    ------------------------------------------------------------------------


    	SET @Qty = (ISNULL(@Qty, 0) * -1)
    	SET @TradeDisc = (ISNULL(@TradeDisc, 0) * - 1)
    	SET @RebateDisc = (ISNULL(@RebateDisc, 0) * -1)
    	SET @OtherDisc = (ISNULL(@OtherDisc, 0) * -1)
    	SET @NetAmount = (ISNULL(@NetAmount, 0) * -1)
    	SET @TaxAmount = (ISNULL(@TaxAmount, 0) * -1)
    	SET @TotalCost = (ISNULL(@TotalCost, 0) * -1)


		INSERT INTO AO_GRV_Details
            (
                AO_GRV_ID,
                AP_Products_ID,
                Qty,
                Unit_Price,
                Trade_Discount_Amount,	
                Rebate_Discount_Amount,
                Other_Discount_Amount,
                Net_Amount,
                Sys_AW_Tax_Codes_ID,
                Tax_Amount,
                Total_Cost,
                [User_ID],
                AW_User_Companies_ID
            )

		VALUES
            (
                @AO_GRV_ID,
                @AP_Products_ID,
                @Qty,
                @Unit_Last_Cost,
                @TradeDisc,
                @RebateDisc,
                @OtherDisc,
                @NetAmount,
                @Tax_Code_ID,
                @TaxAmount,
                @TotalCost,
                @UserID,
                @CompanyID
            )


        --> NEW 30/05/08: INCLUDE UPDATE LAST COST
		UPDATE AP_Products 
		SET Last_Cost = @Unit_Last_Cost,
            Average_Cost = @New_Average_Cost,
            On_Hand = @New_On_Hand,
            [User_ID] = @UserID  
		WHERE AP_Products_ID = @AP_Products_ID
    
		--Select @Prev_Last_Cost As '@Prev_Last_Cost', @Unit_Last_Cost As '@Unit_Last_Cost'
		
        -- NEW v6.0 RL - Insert details into AP_Inventory_Adjustments table
		--IF @Prev_Last_Cost <> @Unit_Last_Cost
		--	BEGIN
                --> Assign the Adjustment Type
                SET @AdjustmentType = 7    --Goods Returned

				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID

                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                       SET @Note = 'Goods Return Adjustment by '
                    END

				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID
                    )
            	VALUES
                    (
                        @AP_Products_ID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    @Prev_Job_Reserved,
            			@Prev_Sales_Order_Reserved,
            		    @Prev_Quote_Reserved,
            			@Unit_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			@Prev_Job_Reserved ,
            			@Prev_Sales_Order_Reserved,
            			@Prev_Quote_Reserved,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID
                    )

         --   END
    
    END
GO

--51 sp_RPT_AS_Sales_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_Sales_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_Sales_Products]
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Products
--Purpose       :Sales by product filtered by Customer, cashier or sales rep
--Functionality :
--Date          :2014-05-13
--Authors       :RL
--Release		:V6.0
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Products]
    (
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @Option varchar(20), --Customer, Customer Type, Customer Group, Cashier, Sales Rep, Sales Area
        
        @CustomerChkAll int,
        @CustomerID int,
        @CustomerGroupChkAll int,
        @CustomerGroupID int,
        @CustomerTypeChkAll int,
        @CustomerTypeID int,
        @CashierChkAll int,
        @CashierID int,
        @SalesRepChkAll int,
        @SalesRepID int,
        @SalesAreaChkAll int,
        @SalesAreaID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '

    IF @Option = 'Customer'
    BEGIN
        SET @sql = @sql + ' c.AC_Customers_ID AS [HeaderID], '
		SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
		SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
		SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [PFilter], '
	END
    ELSE
    IF @Option = 'Customer Group'
        SET @sql = @sql + ' cg.Lup_AC_Customer_Groups_ID AS [HeaderID], ' +
						  ' cg.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Customer Type'
        SET @sql = @sql + ' ct.Lup_AC_Customer_Types_ID AS [HeaderID], ' +
						  ' ct.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Cashier'
    BEGIN
        SET @sql = @sql + ' u.AW_Users_ID AS [HeaderID], '            
		SET @sql = @sql + ' ISNULL(u.FirstName, '''') + '' '' + '
		SET @sql = @sql + ' ISNULL(u.Surname, '''') AS [PFilter], '            
	END
    ELSE
    IF @Option = 'Sales Rep'
        SET @sql = @sql +
            ' sr.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' sr.[Description] AS [PFilter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' sa.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' sa.[Description] AS [PFilter], '
  
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code '
    SET @sql = @sql + ' + '' - '' + '
    SET @sql = @sql + ' ISNULL(p.Description,'''') AS [ProductFilter], '   
    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Original_Price) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (d.Original_Price * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
--    SET @sql = @sql + '      LEFT JOIN AW_Users u '
--    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Customer_Groups cg ' +
            '        ON c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Customer_Types ct' +
            '        ON c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID '
        SET @sql = @sql +
            '    LEFT JOIN AW_Users u ' +
            '        ON h.User_ID = u.AW_Users_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps sr ' +
            '        ON h.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID '
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas sa ' +
            '        ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)'

    IF @CustomerChkAll = 0
        SET @sql = @sql +' AND h.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    
    IF @CustomerGroupChkAll = 0
		SET @sql = @sql +' AND cg.Lup_AC_Customer_Groups_ID = ' + CONVERT(varchar(10), @CustomerGroupID) + ' '
    
    IF @CustomerTypeChkAll = 0
		SET @sql = @sql +' AND ct.Lup_AC_Customer_Types_ID = ' + CONVERT(varchar(10), @CustomerTypeID) + ' '
    
    IF @CashierChkAll = 0
		SET @sql = @sql +' AND u.User_ID = ' + CONVERT(varchar(10), @CashierID) + ' '
    
    IF @SalesRepChkAll = 0
		SET @sql = @sql +' AND sr.Lup_AS_Reps_ID = ' + CONVERT(varchar(10), @SalesRepID) + ' '
    
    IF @SalesAreaChkAll = 0
		SET @sql = @sql +' AND sa.Lup_AC_Sales_Areas_ID = ' + CONVERT(varchar(10), @SalesAreaID) + ' '

    SET @sql = @sql +
        ' ORDER BY [PFilter], [ProductCode], [Product] '

--PRINT @sql

EXEC (@sql)
GO

--52 sp_AP_Update_Inventory_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Details]
GO
--> NEW 05/06/03: Calculate AVERAGE COST

--------------------------------------------------------------------------------
--Description   :sp_AP_Product_Inventory_Details
--Purpose       :Updates Product Last_Cost, On_Hand & Reserved for ONE product in GRV
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2002/02/13
--Authors       :TB
--Version       :1.0.0
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Moved the Reval/Deval Adjustment here from
--              :           sp_AO_Insert_OR_Update_GRV_Detail
--              :04/06/02 - Added text to @Note for normal Stock Adjustments
--              :                and ensured that AP_Inventory_Adjustments is
--              :                for new LastCost AND OnHand adjustments
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--              :05/06/03 - Added COST-OF-SALES / INVENTORY GL adjustments
--              :           GL Journal and GL Transaction for INVENTORY CONTROL
--              :           entries if @COS_Adjust <> 0
--              :06/08/03 - Modified C.O.S. Adjustment GL Transaction Type
--              :           from 22 (Accounts Receivable - Journal)
--              :           to 15 (General Journal - Normal)
--              :04/09/03 - Added to GL Post Purchases/Sales to Inventory/C.O.S.
--              :           ONLY IF chkGRVtoInventoryCOS parameter is vbChecked
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :18/10/03 - Added @GRV_ID input parameter to get the GRV
--              :           Delivery_Note_Number as GLTran RefNo
--              :08/01/04 - Added Inventory Adjustment Type field Sys_AP_Adjustment_Types_ID
--              :26/05/05 - Added match the Accounting Period of the CALENDAR DAY
--              : ********  FIX the above LATER to match the Accounting Period of the GRV
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--2004.4.5      :16/07/09 - Removed check 'IF @NextGLTranID = 0' when creating NORMAL JOURNAL header
--              :           for the C.O.S. Adjustment if item was sold when it was in NEGATIVE On-Hand
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.1      :04/05/11 - Cleaned up comments
--2004.5.2      :06/07/11 - Removed writing an Adjustment if On_Hand is changed
--              :           CANNOT find a reason WHY an Adjustment is required
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Details]
    (
        @GRV_ID int,
    	@ProductID int,
    	@New_Last_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_Average_On_Hand_Value money,
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProductDesc varchar(50),
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
    		@Month tinyint,
    		@Year int,
    		@YearID int,
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30)


    SET @AdjustmentType = 5    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProductDesc = ISNULL([Description], ''),
               @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID


        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


        SET @Qty = @New_On_Hand - @Prev_On_Hand
        SET @COS_Adjust = 0
        SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details

        ------------------------------------------------------------------------
        --> Calculate AVERAGE COST
        ------------------------------------------------------------------------
        --> Initialise Average_Cost
        IF @Prev_Average_Cost = 0
            BEGIN
                SET @Prev_Average_Cost = @New_Last_Cost
            END


        --> If On Hand NEGATIVE then do a Cost Adjustment 
        IF @Prev_On_Hand < 0            -- On_Hand was negative
            BEGIN
                IF @New_On_Hand <= 0    -- On_Hand still negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * @Qty, 2)
                        SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                    END
                ELSE                    -- On_Hand comes out of negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
                        SET @New_Average_Cost = @New_Last_Cost
                    END
            END
        ELSE                            -- On_Hand was positive
            BEGIN
                IF @New_On_Hand <> 0    -- Create a NEW Average Cost
                    BEGIN
                        SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
                                                       (@Qty * @New_Last_Cost)) / @New_On_Hand, 2)
                    END
            END
        ------------------------------------------------------------------------

    	UPDATE AP_Products
        SET Last_Cost = @New_Last_Cost,
            Average_Cost = @New_Average_Cost,
            On_Hand = @New_On_Hand,
            Job_Reserved = @New_Job_Reserved,
            Sales_Order_Reserved = @New_Sales_Order_Reserved,
            Quote_Reserved = @New_Quote_Reserved,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID


        --> CONTINUOUS INVENTORY ONLY - INSERT a GL COST-OF-SALES adjustment
        --                if item was sold when it was in NEGATIVE On-Hand
        IF @COS_Adjust <> 0
            BEGIN

                --> Get CONTINUOUS INVENTORY parameter setting
                SELECT @GRInventoryCOS = Control_Value
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkGRVtoInventoryCOS' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID


                IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
                    BEGIN

                        --> The above should match the Accounting Period of the GRV !!
                        SET @Month = DATEPART(mm, getdate())
                        SET @Year = DATEPART(yy, getdate())

                        SELECT @YearID = Slu_AW_Years_ID
                        FROM Slu_AW_Years
                        WHERE [Description] = CONVERT(varchar(10), @Year)

                        IF @Month = 0 OR @YearID = 0
                            BEGIN
                                SELECT @Month = Slu_AW_Months_ID,
                                       @YearID = Slu_AW_Years_ID
                                FROM AW_User_Companies
                                WHERE AW_User_Companies_ID = @CompanyID
                            END

                        SET @RefNo = 'GRV ' + CONVERT(varchar(10), @GRV_ID)
                        SET @RefNo = LEFT(@RefNo, 20)

                        SET @Narration = LEFT('GRV C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
                        --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                15,
                                @CompanyID

                        SET @GLTranDate = getdate()

        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                @GLTranDate,
                                @NextGLTranID,
                                @Narration,
                                @Month,
                                @YearID,
                                @UserID,
                                @CompanyID

                        --> Update INVENTORY ADJUSTMENTS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 107    --Inventory Adjustments Control
        
                        --> Create JOURNAL DETAIL for Cost Of Sales
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Cost Of Sales
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID
        
                        --> Reverse signs to balance double entry
                        SET @COS_Adjust = @COS_Adjust * -1
        
                        --> Update INVENTORY CONTROL
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 601    --Inventory
        
                        --> Create JOURNAL DETAIL for Inventory
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Inventory
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID

                    END
            END


        --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail - Commented 2004.5.2
-- 		IF @Prev_Last_Cost <> @New_Last_Cost OR
--            @Prev_On_Hand <> @New_On_Hand

        -- NEW 2004.5.2 - CANNOT find a reason WHY an Adjustment is required if On_Hand is changed
		IF @Prev_Last_Cost <> @New_Last_Cost


			BEGIN

                --> Assign the Adjustment Type
                IF @Prev_Last_Cost <> @New_Last_Cost
                    BEGIN
                        SET @AdjustmentType = 5    --GRV Reval/Deval
                    END
                ELSE
                    BEGIN
                        SET @AdjustmentType = 4    --GRV Adjustment
                    END


				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID


                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                        IF @Prev_Last_Cost <> @New_Last_Cost
                            SET @Note = 'Goods Received Reval/Deval by '
                        ELSE
                            SET @Note = 'Goods Received Adjustment by '
                    END
                ELSE
                IF @Note = 'Goods Received by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
                    BEGIN
                        SET @AdjustmentType = 2    --Goods Received
                    END


				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    @Prev_Job_Reserved,
            			@Prev_Sales_Order_Reserved,
            		    @Prev_Quote_Reserved,
            			@New_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			@New_Job_Reserved ,
            			@New_Sales_Order_Reserved,
            			@New_Quote_Reserved,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    END 			


SET NOCOUNT OFF
GO

--53 sp_AP_Update_Product_Filters
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_Filters]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_Filters]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Filters
--Purpose       :
--Date          :2005/04/27
--Authors       :TB
--MODS          :
--2004.3.4      :20/02/07 - Added Product Location field
--              :20/02/07 - Added Purchase Category field
--2004.3.5      :15/06/07 - Added @chkLinkOnly input parameter
--2004.5.7 RGL  :2012-10-20 - Added @Weight and @Levy_Product input parameter
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Filters]
	(
        @ProductID int,
        @Type int,
        @Group int,
        @Department int,
        @Location int,
        @Supplier int,
        @Manufacturer int,
        @Purchase int,
        @Active int,
        @chkLinkOnly tinyint,
        @Levy int,
        @Weight decimal(9,3),
        @UserID int      
	)
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0
  
    IF @chkLinkOnly = 1
        BEGIN
            IF EXISTS
                (
                    SELECT AP_Products_ID
                    FROM AP_Products
                    WHERE AP_Products_ID = @ProductID
        
                )
                BEGIN
                    UPDATE AP_Products
                    SET Lup_AP_Product_Types_ID = @Type,
                        Lup_AP_Product_Groups_ID = @Group,
                        Lup_AP_Product_Departments_ID = @Department,
                        Lup_AP_Product_Locations_ID = @Location,
                        Lup_AP_Product_Manufacturers_ID = @Manufacturer,
                        Lup_AP_Purchase_Categories_ID = @Purchase,
                        Slu_AW_Active_ID = @Active,
                        Levy_AP_Product_ID = @Levy,
                        Lup_AP_AW_Weight_ID = 2, --RGL 2012-10-26 Kilogram No more space on product filter screen
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @ReturnValue = 1
        
                END
        END
    ELSE
        BEGIN
            IF EXISTS
                (
                    SELECT AP_Products_ID
                    FROM AP_Products
                    WHERE AP_Products_ID = @ProductID
        
                )
                BEGIN
                    UPDATE AP_Products
                    SET Lup_AP_Product_Types_ID = @Type,
                        Lup_AP_Product_Groups_ID = @Group,
                        Lup_AP_Product_Departments_ID = @Department,
                        Lup_AP_Product_Locations_ID = @Location,
                        Default_Supplier_ID = @Supplier,
                        Lup_AP_Product_Manufacturers_ID = @Manufacturer,
                        Lup_AP_Purchase_Categories_ID = @Purchase,
                        Slu_AW_Active_ID = @Active,
                        Levy_AP_Product_ID = @Levy,
                        Lup_AP_AW_Weight_ID = 2, --RGL 2012-10-26 Kilogram No more space on product filter screen
                        Product_Weight = @Weight,
                        [User_ID] = @UserID                        
                    WHERE AP_Products_ID = @ProductID
        
                    SET @ReturnValue = 1
        
                END
        END

RETURN @ReturnValue
GO

--54 sp_AP_Update_Adjusted_Inventory_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Adjusted_Inventory_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Adjusted_Inventory_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Adjusted_Inventory_Details
--Purpose       :Inserts Stock Adjustments
--   			:    NB: Any mods must sync with sp_AP_Update_Inventory_Details
--              :    that is used for Goods Received and Returned Vouchers (GRV)
--Functionality :Handles Stock Adjustment Types 1, 3, 6
--Date          :2002/02/13
--Authors       :TB
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Moved the Reval/Deval Adjustment here from
--              :           sp_AO_Insert_OR_Update_GRV_Detail
--              :04/06/02 - Added text to @Note for normal Stock Adjustments
--              :                and ensured that AP_Inventory_Adjustments is
--              :                for new LastCost AND OnHand adjustments
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :31/05/03 - Added calculate and update AVERAGE COST in AP_Products
--              :08/01/04 - Added Inventory Adjustment Type field Sys_AP_Adjustment_Types_ID
--              :09/09/04 - Added @AdjustmentType = 6 code to ID if Stock Take-on
--2004.4.0      :09/07/08 - Add new update General Ledger with the value of Stock Adjustments.
--              :           A General Journal is created for each adjustment and posted to the
--              :           Inventory and Cost-of-Sales GL accounts
--              :09/07/08 - Added @Month and @Year input parameters for GL entry
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--2004.4.5      :15/07/09 - Reworked update General Ledger with the value of Stock Adjustments.
--              :           Previous Qty Adjustment was NOT inserted in GL if Costs not also adjusted
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.0      :06/04/11 - Reworked to prevent behaviour at TC Germiston Manufacturing that
--              :           writes ONLY ONE leg of the Journal and GL Transaction entries, but
--              :           increments ID of GLTran table BUT DOES NOT WRITE THE TRANSACTION 
--              :           then puts GL out of balance !!!!!!!!!!!!!!!!
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Adjusted_Inventory_Details]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
        	@Prev_On_Hand decimal(9,3),
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @Prev_Average_Cost money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_On_Hand_Value money,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount1 int,
            @GLControlAccount2 int,
            @Diff_On_Hand decimal(9,3),
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 1            --Intialize as 'Adjustment' type
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    -- Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
		   @Prev_On_Hand = ISNULL(On_Hand, 0),
		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
    	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
           @Prev_Average_Cost = ISNULL(Average_Cost, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = @New_On_Hand,
        Job_Reserved = @New_Job_Reserved,
        Sales_Order_Reserved = @New_Sales_Order_Reserved,
        Quote_Reserved = @New_Quote_Reserved,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Average_Cost <> @New_Average_Cost OR
       @Prev_On_Hand <> @New_On_Hand
		BEGIN

            SET @Diff_On_Hand = 0
            SET @Diff_Value = 0

            ------------------------------------------------------------
            --> Assign Qty Adjustment Type
            ------------------------------------------------------------
            IF @Prev_On_Hand <> @New_On_Hand
                BEGIN
                    SET @Diff_On_Hand = @New_On_Hand - @Prev_On_Hand

                    SET @AdjustmentType = 1        --QTY Adjustment ONLY
                END

            ------------------------------------------------------------
            --> IF NOT Qty Adjustment then USE Previous On_Hand
            ------------------------------------------------------------
            IF @Diff_On_Hand = 0
                BEGIN
                    SET @Diff_On_Hand = @Prev_On_Hand
                END

            ------------------------------------------------------------
            --> Assign Reval/Deval Adjustment Type
            ------------------------------------------------------------
            IF @Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost
                BEGIN
                    SET @AdjustmentType = 3        --COST Adjustment ONLY
                END

            ------------------------------------------------------------
            --> Assign Stock Take-On Adjustment Type
            ------------------------------------------------------------
    		IF @Prev_On_Hand <> @New_On_Hand AND
              (@Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost)
    			BEGIN
                    SET @AdjustmentType = 6       --QTY AND COST Adjustment
                END


            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            IF @AdjustmentType = 1        --QTY Adjustment ONLY (@Diff_*_Cost = 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Qty by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Average_Cost), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Last_Cost), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 3        --COST Adjustment ONLY (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Costs by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Average_Cost - @Prev_Average_Cost)), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 6        --QTY AND COST Adjustment (Stock Take-On) (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Take-On by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Average_Cost * @Prev_On_Hand), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
							--RL V6.0 2014-10-15
                           --SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Last_Cost * @Prev_On_Hand), 2)
                           SET @Diff_Value = ROUND((@New_Last_Cost * @New_On_Hand) - (@Prev_Last_Cost * @Prev_On_Hand), 2)
                        END
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)


            ------------------------------------------------------------------------------
            --> INSERT GL Entries here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    --> Create NORMAL JOURNAL header
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END

                    --> Update INVENTORY CONTROL
                    SELECT @GLControlAccount1 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 601


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount1,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount1,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID


                    --> Update NEW Inventory Adjustments CONTROL
    				SELECT @GLControlAccount2 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 107


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount2,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount2,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------

            IF LTRIM(RTRIM(@Note)) = ''
                BEGIN
                    IF @AdjustmentType = 1
                        BEGIN
                            SET @Note = 'Stock Adjust Qty by '
                        END
                    ELSE
                    IF @AdjustmentType = 3
                        BEGIN
                            SET @Note = 'Stock Adjust Costs by '
                        END
                    ELSE
                    IF @AdjustmentType = 6
                        BEGIN
                            SET @Note = 'Stock Adjust Take-On by '
                        END
                END
            ELSE
                BEGIN
                    SET @Note = RTRIM(LTRIM(@Note)) + ' by '
                END


			SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


            ------------------------------------------------------------
            --> INSERT the Adjustment
            ------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        		    @Prev_Job_Reserved,
        			@Prev_Sales_Order_Reserved,
        		    @Prev_Quote_Reserved,
        			@New_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@New_Job_Reserved ,
        			@New_Sales_Order_Reserved,
        			@New_Quote_Reserved,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID



SET NOCOUNT OFF
GO

--55 sp_AP_Update_Inventory_Cost_Adjustments_Split_Types
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Cost_Adjustments_Split_Types
--Purpose       :Inserts SPLIT Cost Adjustments by PRODUCT TYPE and UPDATE GL
--              :    1. Inventory Control or
--              :    2. Split Inventory Control by PRODUCT TYPE if parameter is set
--Functionality :Handles Inventory Cost Adjustment Types 3 - Reval/Deval
--              :INSERT Stock Adjustment ONLY IF EITHER LastCost or AvgCost changed
--              :UPDATE GL ONLY IF ((NewLastCost or NewAvgCost) * OnHand) change has a VALUE 
--Date          :2011/04/17
--Authors       :TB
--Mods          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Avg_Cost money,
    	@New_Std_Cost money,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Avg_Cost money,
        	@OnHand decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount int,
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @SplitGRVparameter varchar(10),
            @SplitGRVTypes int,
            @TypeDescription varchar(50),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 3            --Reval/Deval
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    --> Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


    --> Get the CURRENT Product values
	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
           @Prev_Avg_Cost = ISNULL(Average_Cost, 0),
		   @OnHand = ISNULL(On_Hand, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Avg_Cost,
        Standard_Cost = @New_Std_Cost
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Avg_Cost <> @New_Avg_Cost
		BEGIN 
            -------------------------------------------------------
            --> Get Split GRV Stock Receipts to GL INVENTORY accounts parameter
            -------------------------------------------------------
            SET @SplitGRVparameter = '0'

            SELECT @SplitGRVparameter = Control_Value
            FROM Sys_AW_Options
            WHERE Control_Type = 'CheckBox' AND
                  Control_Name = 'chkUseProductPurchasesGL' AND
                  Control_Index = 0 AND
                  AW_User_Companies_ID = @CompanyID

            -------------------------------------------------------
            --> ONLY set @SplitGRVTypes if @SplitGRVparameter = '1'
            -------------------------------------------------------
            SET @SplitGRVTypes = 0

            IF @SplitGRVparameter = '1'
                BEGIN
                    SET @SplitGRVTypes = 1
                END

            -------------------------------------------------------
            --> Get the INVENTORY CONTROL if NOT Split GRV Stock Receipts parameter
            -------------------------------------------------------
            --> Update INVENTORY CONTROL
            SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 601        --Inventory Control

            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            SET @Diff_Value = 0
            SET @Narration = 'Cost Adjusment by '

            IF @ValuationMethod = 0        -- Average Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Avg_Cost - @Prev_Avg_Cost)), 2)
                END
            ELSE
            IF @ValuationMethod = 1        -- Last Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> NEW 2004.4.3 - Get the Product TYPE Description
            ------------------------------------------------------------------------------
            SET @TypeDescription = ''

			SELECT @TypeDescription = ISNULL(t.Description, '')
			FROM AP_Products p
                LEFT JOIN Lup_AP_Product_Types t
                    ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
			WHERE p.AP_Products_ID = @ProductID


            SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)

            ------------------------------------------------------------------------------
            --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    ---------------------------------------------------------------------
                    --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                    ---------------------------------------------------------------------
                    SET @GLAdjustID = 0

                    SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @AdjustGLDescription AND
                          Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                          Slu_AW_Active_ID = 1


                    IF @GLAdjustID = 0
                        BEGIN
             				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                    @AdjustGLDescription,
                                                    14,
                                                    @UserID,
                                                    @CompanyID
                        END

                    ---------------------------------------------------------------------
                    --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                    ---------------------------------------------------------------------
                    IF @SplitGRVTypes = 1
                        BEGIN
                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                  Slu_AW_Active_ID = 1


                            IF @GLInventoryID = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
                            ---------------------------------------------------------------------
                        END
                    ---------------------------------------------------------------------


                    --> Create NORMAL JOURNAL header for ADJUSTMENT
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    IF @SplitGRVTypes = 1
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran


                            --> Create GL TRANSACTION for SPLIT GL Inventory Account
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLInventoryID,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END
                    ELSE
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control 601
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for Inventory Control 601
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLControlAccount,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAdjustID,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLAdjustID,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Avg_Cost,
        			@OnHand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Avg_Cost,
        			@OnHand,
        			0 ,
        			0,
        			0,
        			@Narration,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID



SET NOCOUNT OFF
GO

--56 sp_AP_Post_Stock_Take_Adjustments
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Post_Stock_Take_Adjustments]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Post_Stock_Take_Adjustments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Post_Stock_Take_Adjustments
--Purpose       :Inserts Stock Adjustments from Stock Take Procedure
--              :    1. Normal Inventory/Cost-of-Sales Control or
--              :    2. Split Inventory/Adjustment Control by PRODUCT TYPE
--              :
--Functionality :Uses CURSOR. Only Qty Stock Adjustments (Type 1)
--              :Can be used to ZERO all stock if Total Count = 0
--              :Uses TRANSACTION ISOLATION LEVEL SERIALIZABLE
--Date          :2009/02/22
--Authors       :TB
--Mods          :
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Post_Stock_Take_Adjustments]
    (
    	@StockTakeProcedureID int,
        @SplitGRVGL tinyint,
        @SplitADJGL tinyint,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @StockTakeID int,
            @ProductID int,
            @UnitCost money,
            @OnHand decimal(9,3),
            @Variance decimal(9,3),
            @ProductCode varchar(20),
    		@UserFirstName varchar(40),
            @AdjustmentTypeID tinyint,
            @AdjustValue money,
            @AdjustTotal money,
            @Narration varchar(50),
            @NextGLTranID int,
            @JNLHeaderID int,
            @InsertGLTran bit,
            @AdjustDate datetime,
            @GLInventoryControlID int,
            @GLCOSControlID int,
    	    @Note varchar(70),
            @Prev_On_Hand decimal(9,3),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
            @New_On_Hand decimal(9,3),
            @New_Last_Cost money,
            @New_Average_Cost money,
            @ProcedureDate varchar(30),

            @TypeDescription varchar(50),
            @TypeTotal money,
            @SplitGRVparameter varchar(10),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ReturnValue int


    --> Get the User Name
	SELECT @UserFirstName = LEFT(ISNULL(FirstName, ''), 20)
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --> Get the Stock Take Procedure details
	SELECT @ProcedureDate = CONVERT(varchar(30), Procedure_Date, 120)
	FROM AP_Stock_Take_Procedures
	WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    SET @ProcedureDate = LEFT(@ProcedureDate, 20)


    --> Get INVENTORY CONTROL
    SELECT @GLInventoryControlID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 601    --Inventory Control


    --> Get INVENTORY ADJUSTMENTS CONTROL
	SELECT @GLCOSControlID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 107    --Inventory Adjustments Control


    --> Initialize vars
    SET @ReturnValue = 0
    SET @AdjustmentTypeID = 1            --Intialize as 'Qty Adjustment' type
    SET @Narration = LEFT(('Stock Take ' + @ProcedureDate + ' Adjust by ' + @UserFirstName), 50) 
	SET @Note = LEFT(('Stock Take ' + @ProcedureDate + ' Adjust by ' + @UserFirstName), 70) 
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = DO NOT insert a GL Transaction in JNL Details
    SET @AdjustTotal = 0
    SET @AdjustDate = getdate()


    BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
        BEGIN TRANSACTION

        ------------------------------------------------------------
        --> INSERT Stock Adjustment in AP_Inventory_Adjustments
        ------------------------------------------------------------
    	DECLARE Adjustment_Cursor CURSOR FOR
            (
                SELECT AP_Products_Stock_Takes_ID,
                       AP_Products_ID,
                       ISNULL(Unit_Cost, 0),
                       ISNULL(On_Hand, 0),
                       ISNULL(Variance, 0),
                       ROUND(ISNULL(Unit_Cost, 0) * ISNULL(Variance, 0), 2)
                FROM AP_Products_Stock_Takes
                WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
                      ISNULL(Variance, 0) <> 0
            )

    	OPEN Adjustment_Cursor

        	FETCH NEXT FROM Adjustment_Cursor 
        	INTO
                @StockTakeID,
                @ProductID,
                @UnitCost,
                @OnHand,
                @Variance,
                @AdjustValue

        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                --> @AdjustValue = NEGATIVE if @Variance NEGATIVE (Stock Loss)
                SET @AdjustTotal = @AdjustTotal + @AdjustValue

                --> Get PREV (In case it changed since Stock Take Procedure)
            	SELECT @Prev_On_Hand = ISNULL(On_Hand, 0),
                       @Prev_Last_Cost = ISNULL(Last_Cost, 0),
                       @Prev_Average_Cost = ISNULL(Average_Cost, 0),
                       @ProductCode = ISNULL(Product_Code, '')
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID

                --> Set NEW
                SET @New_On_Hand = @Prev_On_Hand + @Variance
                SET @New_Last_Cost = @Prev_Last_Cost
                SET @New_Average_Cost = @Prev_Average_Cost

                --> Adjust CURRENT On_Hand with COUNT VARIANCE AND COST
                --  because THAT WAS THE ACTUAL COST when the Stock Take WAS MADE !!
            	UPDATE AP_Products
                SET On_Hand = @New_On_Hand,
                [User_ID] = @UserID
            	WHERE AP_Products_ID = @ProductID


                ------------------------------------------------------------
                --> INSERT Stock Adjustment table
                ------------------------------------------------------------
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentTypeID,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    0,
            			0,
            		    0,
            			@New_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			0 ,
            			0,
            			0,
            			@Note,
            			@AdjustDate,
            			@UserID,
            			@CompanyID
                    )
                ------------------------------------------------------------

            	FETCH NEXT FROM Adjustment_Cursor 
            	INTO
                    @StockTakeID,
                    @ProductID,
                    @UnitCost,
                    @OnHand,
                    @Variance,
                    @AdjustValue

        	END

    	CLOSE Adjustment_Cursor

    	DEALLOCATE Adjustment_Cursor


------------------------------------------------------------
--> INSERT Split GL per PRODUCT TYPE Journal here
------------------------------------------------------------


        IF @SplitGRVGL = 1 OR @SplitADJGL = 1
            BEGIN
                ------------------------------------------------------------
                --> INSERT Stock Adjustment in AP_Inventory_Adjustments
                ------------------------------------------------------------
            	DECLARE Type_Cursor CURSOR FOR
                    (
                        SELECT ISNULL(t.Description, ''),
                               SUM(ROUND(ISNULL(st.Unit_Cost, 0) * ISNULL(st.Variance, 0), 2))
                        FROM AP_Products_Stock_Takes st
                            INNER JOIN AP_Products p
                                ON st.AP_Products_ID = p.AP_Products_ID
                            INNER JOIN Lup_AP_Product_Types t
                                ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
                        WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
                              ISNULL(Variance, 0) <> 0
                        GROUP BY t.Description
                    )

            	OPEN Type_Cursor

                	FETCH NEXT FROM Type_Cursor 
                	INTO
                        @TypeDescription,
                        @TypeTotal


                	WHILE @@FETCH_STATUS = 0
                	BEGIN

                        IF LTRIM(RTRIM(@TypeDescription)) = ''
                            BEGIN
                                SET @TypeDescription = '<None>'
                            END

                        SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
                        SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)


                        ------------------------------------------------------------------------------
                        --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
                        ------------------------------------------------------------------------------
                        IF @TypeTotal <> 0
                            BEGIN
                                IF @SplitADJGL = 1
                                    BEGIN
                                        ---------------------------------------------------------------------
                                        --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                                        ---------------------------------------------------------------------
                                        SET @GLAdjustID = 0

                                        SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                                        FROM AB_Accounts
                                        WHERE AW_User_Companies_ID = @CompanyID AND
                                             [Description] = @AdjustGLDescription AND
                                              Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                                              Slu_AW_Active_ID = 1


--                                        IF @GLAdjustID IS NULL OR @GLAdjustID = 0
                                        IF @GLAdjustID = 0
                                            BEGIN
                                 				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                                        @AdjustGLDescription,
                                                                        14,
                                                                        @UserID,
                                                                        @CompanyID
                                            END
                                    END

                                ---------------------------------------------------------------------
                                --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                                ---------------------------------------------------------------------
                                IF @SplitGRVGL = 1
                                    BEGIN
                                        ---------------------------------------------------------------------
                                        --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                                        ---------------------------------------------------------------------
                                        SET @GLInventoryID = 0

                                        SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                                        FROM AB_Accounts
                                        WHERE AW_User_Companies_ID = @CompanyID AND
                                             [Description] = @InventoryGLDescription AND
                                              Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                              Slu_AW_Active_ID = 1


--                                        IF @GLInventoryID IS NULL OR @GLInventoryID  = 0
                                        IF @GLInventoryID  = 0
                                            BEGIN
                                 				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                                        @InventoryGLDescription,
                                                                        7,
                                                                        @UserID,
                                                                        @CompanyID
                                            END
                                        ---------------------------------------------------------------------
                                    END
                                ---------------------------------------------------------------------

                                ---------------------------------------------------------------------
                                --> Create JOURNAL HEADER for ADJUSTMENT Product Type
                                ---------------------------------------------------------------------
                                IF @NextGLTranID = 0
                                    BEGIN
                         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                                15,
                                                @CompanyID
            
                        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                                @AdjustDate,
                                                @NextGLTranID,
                                                @Narration,
                                                @Month,
                                                @Year,
                                                @UserID,
                                                @CompanyID
                                    END
                                ---------------------------------------------------------------------

                                IF @SplitGRVGL = 1
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Inventory Control
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLInventoryID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran


                                        --> Create GL TRANSACTION for SPLIT GL Inventory Account
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLInventoryID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END
                                ELSE
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Inventory Control 601
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLInventoryControlID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for Inventory Control 601
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLInventoryControlID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END


                                --> Reverse signs to balance double entry
                                SET @TypeTotal = @TypeTotal * -1


                                IF @SplitADJGL = 1
                                    BEGIN
                                        --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLAdjustID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLAdjustID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END
                                ELSE
                                    BEGIN
                                        --> Create JOURNAL DETAIL for Cost-of-Sales 106
                                        EXEC sp_AB_Insert_Journal_Detail
                                                @JNLHeaderID,
                                                @GLCOSControlID,
                                                @TypeTotal,
                                                @Narration,
                                                @UserID,
                                                @CompanyID,
                                                @InsertGLTran

                                        --> Create GL TRANSACTION for Cost-of-Sales 106
                                        EXEC sp_AB_Insert_GL_Transactions
                                                @Narration,
                                                15,
                                                @GLCOSControlID,
                                                @AdjustDate,
                                                @ProductCode,
                                                @Month,
                                                @Year,
                                                @NextGLTranID,
                                                @TypeTotal,
                                                @UserID,
                                                @CompanyID
                                    END

                            END    --IF @TypeTotal <> 0
                        ------------------------------------------------------------

                    	FETCH NEXT FROM Type_Cursor 
                    	INTO
                            @TypeDescription,
                            @TypeTotal

                	END

            	CLOSE Type_Cursor

            	DEALLOCATE Type_Cursor

            END    --IF @SplitGRVGL = 1 OR @SplitADJGL = 1


------------------------------------------------------------
--> INSERT Non-Split GL Single Journal here
------------------------------------------------------------

            ELSE
                BEGIN
                    ------------------------------------------------------------
                    --> INSERT GL - Create NORMAL JOURNAL header for Cost Of Sales
                    ------------------------------------------------------------
                    IF @NextGLTranID = 0
                        BEGIN
                            EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

                			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLInventoryControlID,
                            @AdjustTotal,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLInventoryControlID,
                            @AdjustDate,
                            @ProcedureDate,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @AdjustTotal,
                            @UserID,
                            @CompanyID


                    --> Reverse signs to balance double entry to COST OF SALES
                    SET @AdjustTotal = @AdjustTotal * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLCOSControlID,
                            @AdjustTotal,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCOSControlID,
                            @AdjustDate,
                            @ProcedureDate,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @AdjustTotal,
                            @UserID,
                            @CompanyID

                END
    
------------------------------------------------------------
--> UPDATE Stock Take Procedure
------------------------------------------------------------
    	UPDATE AP_Stock_Take_Procedures
        SET Slu_AW_Months_ID = @Month,
            Slu_AW_Years_ID = @Year,
            AB_Journals_ID = @JNLHeaderID,
            Stock_Adjustment_Total = @AdjustTotal
    	WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID
------------------------------------------------------------

	    COMMIT TRANSACTION

        SET @ReturnValue = 1

    END



RETURN @ReturnValue


SET NOCOUNT OFF
GO

--57 sp_AP_Update_Profit_Protector
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Profit_Protector]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Profit_Protector]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Profit_Protector
--Purpose       :
--Date          :2004/08/05
--Authors       :TB
--MODS          :
--              :09/05/08 - Replaced Maximum Discount% field functionality with
--              :           Minimum GP% functionality
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Profit_Protector]
	(
        @ProductID int,
        @EditPrice tinyint,
        @EditDisc tinyint,
        @MinGP decimal(5,2),
        @ApplyMin tinyint,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Slu_AW_YesNo_Edit_Price = @EditPrice,
                Slu_AW_YesNo_Edit_Discount = @EditDisc,
                Max_Discount_Perc = @MinGP,
                Slu_AW_YesNo_Max_Discount_Perc = @ApplyMin,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
GO

--58 sp_AP_Update_Product_Discount_Groups
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_Discount_Groups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_Discount_Groups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Discount_Groups
--Purpose       :
--Date          :2006/10/07
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Discount_Groups]
	(
        @ProductID int,
        @Group int,
        @UserID	int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Lup_AP_Discount_Groups_ID = @Group,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
GO

--59 sp_AP_Update_Product_CostPlus_Groups
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_CostPlus_Groups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_CostPlus_Groups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_CostPlus_Groups
--Purpose       :
--Date          :2007/07/29
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_CostPlus_Groups]
	(
        @ProductID int,
        @IsCostPlus tinyint,
        @CostPlusGroup int,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Slu_AW_YesNo_Cost_Plus_Item = @IsCostPlus,
                Lup_AP_Markup_Groups_ID = @CostPlusGroup,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
GO

--60 sp_AP_Update_Price_Adjustments
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Price_Adjustments]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Price_Adjustments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Price_Adjustments
--Purpose       :
--Date          :2004/07/20
--Authors       :TB
--MODS          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Price_Adjustments]
	(
        @ProductID int,
        @Selling11 money,
        @Selling12 money,
        @Date1 datetime,
        @Selling21 money,
        @Selling22 money,
        @Date2 datetime,
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_ID
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID

        )
        BEGIN
            UPDATE AP_Products
            SET Price1_Effective_Date = @Date1,
                Price1_Price1 = @Selling11,
                Price1_Price2 = @Selling12,
                Price2_Effective_Date = @Date2,
                Price2_Price1 = @Selling21,
                Price2_Price2 = @Selling22,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
GO

--61 Insert Sales Product Report
IF NOT EXISTS
(
	SELECT Sys_AW_Reports_ID
	FROM Sys_AW_Reports
	WHERE Report_No = '118' 
	AND	Method_Name = 'Show_SalesProducts'
) 
BEGIN
	INSERT INTO Sys_AW_Reports
	(
		Sys_AW_Modules_ID,
		Type_ID,
		Location,
		Report_No,
		Report_Name,
		[Description],
		Object_DLL,
		Class_Name,
		Method_Name
	)
	VALUES
	(
		1,
		0,
		'Sales Reports',
		'118',
		'Sales Products Filtered',
		'Sales Products Filtered',
		'SpSSalesReports',
		'CInterface',
		'Show_SalesProducts'
	)
END
GO

--62 sp_AP_Update_Inbound_Transfer_Cost
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inbound_Transfer_Cost]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inbound_Transfer_Cost]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inbound_Transfer_Cost
--Source        :Lifted from sp_AP_Update_Inventory_Details (Stock Receipt GRV)
--Purpose       :Updates Product Last_Cost, On_Hand for ONE product in INbound Stock Transfer
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2010/10/02
--Authors       :TB
--Mods          :
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inbound_Transfer_Cost]
    (
        @TransferID int,
    	@ProductID int,
        @MonthID tinyint,
        @YearID smallint,
        @TransferType varchar(30),
    	@Transfer_Qty decimal(9,3),
    	@New_Unit_Cost money,
    	@New_Amount money,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @New_Average_Cost money,
            @New_Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30),
            @Note varchar(70)


    SET @AdjustmentType = 5    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID


        SET @New_Qty = @Prev_On_Hand + @Transfer_Qty
        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


        SET @COS_Adjust = 0
        SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details

------------------------------------------------------------------------
--> NEW 04/06/03: Calculate AVERAGE COST
------------------------------------------------------------------------
    --> Initialises Average_Cost
        IF @Prev_Average_Cost = 0
            BEGIN
                SET @New_Average_Cost = @New_Unit_Cost
            END

        IF @Prev_On_Hand < 0            -- On_Hand was negative
            BEGIN
                IF @New_Qty <= 0        -- On_Hand still negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Unit_Cost - @Prev_Average_Cost) * @New_Qty, 2)
                        SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                    END
                ELSE                    -- On_Hand comes out of negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Unit_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
                        SET @New_Average_Cost = @New_Unit_Cost
                    END
            END
        ELSE                            -- On_Hand was positive
            BEGIN
                IF @Transfer_Qty <> 0    -- Create a NEW Average Cost
                    BEGIN
                        SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
                                                       (@Transfer_Qty * @New_Unit_Cost)) / @New_Qty, 2)
                    END
            END
------------------------------------------------------------------------

    	UPDATE AP_Products
        SET Last_Cost = @New_Unit_Cost,
            Average_Cost = @New_Average_Cost,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID


    --> INSERT a GL COST-OF-SALES adjustment for CONTINOUS INVENTORY ONLY
    --                if item was sold when it was in NEGATIVE On-Hand
        IF @COS_Adjust <> 0
            BEGIN

            --> Get Continuous Inventory settings
                SELECT @GRInventoryCOS = Control_Value
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkGRVtoInventoryCOS' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID


                IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = Continuous Inventory = Yes
                    BEGIN
                        SET @RefNo = @TransferType + CONVERT(varchar(10), @TransferID)
                        SET @RefNo = LEFT(@RefNo, 20)

                        SET @Narration = LEFT(@TransferType + 'C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
                    --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                15,
                                @CompanyID

                        SET @GLTranDate = getdate()

        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                @GLTranDate,
                                @NextGLTranID,
                                @Narration,
                                @MonthID,
                                @YearID,
                                @UserID,
                                @CompanyID

                    --> Update INVENTORY ADJUSTMENTS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 107    --Inventory Adjustments Control
        
                    --> Create JOURNAL DETAIL for Cost Of Sales
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                    --> Create GL TRANSACTION for Cost Of Sales
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @MonthID,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID
        
                    --> Reverse signs to balance double entry
                        SET @COS_Adjust = @COS_Adjust * -1
        
                    --> Update INVENTORY CONTROL
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 601    --Inventory
        
                    --> Create JOURNAL DETAIL for Inventory
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                    --> Create GL TRANSACTION for Inventory
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @MonthID,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID

                    END
            END


    --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail
		IF @Prev_Last_Cost <> @New_Unit_Cost OR
           @Prev_On_Hand <> @Transfer_Qty
			BEGIN 

                --> Assign the Adjustment Type
                IF @Prev_Last_Cost <> @New_Unit_Cost
                    BEGIN
                        SET @AdjustmentType = 5    --TRF Reval/Deval
                    END
                ELSE
                    BEGIN
                        SET @AdjustmentType = 4    --TRF Adjustment
                    END

				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID


                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                        IF @Prev_Last_Cost <> @New_Unit_Cost
                            SET @Note = @TransferType + 'Reval/Deval by '
                        ELSE
                            SET @Note = @TransferType + 'Adjustment by '
                    END
                ELSE
                IF @Note = @TransferType + 'by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
                    BEGIN
                        SET @AdjustmentType = 2    --Goods Received
                    END


				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 

                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    0,
            			0,
            		    0,
            			@New_Unit_Cost,
                        @New_Average_Cost,
            			@Transfer_Qty,
            			0 ,
            			0,
            			0,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    
    END 			

SET NOCOUNT OFF
GO

--63 fn_AP_Products_Job_Reserved
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[fn_AP_Products_Job_Reserved]') 
            AND type in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[fn_AP_Products_Job_Reserved]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Job_Reserved
--Purpose       :SUM all JOB CARD for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Job_Reserved]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD 
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 2)
              
	RETURN(@ReservedQTY)
   
END
GO

--64 fn_AP_Products_Sales_Order_Reserved
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[fn_AP_Products_Sales_Order_Reserved]') 
            AND type in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[fn_AP_Products_Sales_Order_Reserved]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Sales_Order_Reserved
--Purpose       :SUM all Sales Orders for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Sales_Order_Reserved]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- Sales Order
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 16)
              
	RETURN(@ReservedQTY)
   
END
GO

--65 fn_AP_Products_Quoted
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[fn_AP_Products_Quoted]') 
            AND type in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[fn_AP_Products_Quoted]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_Products_Quoted
--Purpose       :SUM all Quotes for one Product
--Parameters    :
--Date          :2014/05/22
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Products_Quoted]
    (
        @ProductID int
    )

RETURNS float
AS
BEGIN

	DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- Quotes
    -------------------------------------------------------------------------------
	SELECT @ReservedQTY = ISNULL(SUM(d.Quantity), 0)
	FROM AS_Transaction_Details d
		INNER JOIN AS_Transactions h
		ON d.AS_Transactions_ID = h.AS_Transactions_ID
	WHERE d.AP_Products_ID = @ProductID 
		AND h.Slu_AW_Active_ID = 1 
		AND (h.Sys_AW_Transaction_Types_ID = 1)
              
	RETURN(@ReservedQTY)
   
END
GO

--66 sp_AS_Select_Delivery_Address_Hist
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
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
    (    	    	
    	@AC_Customers_ID int
    )
AS 

	SELECT 
		ISNULL(Customer_Name,'') AS 'Customer_Name',
		ISNULL(Inv_Address1,'') AS 'Inv_Address1',
		ISNULL(Inv_Address2,'') AS 'Inv_Address2',
		ISNULL(Inv_City,'') AS 'Inv_City',
		ISNULL(Inv_Code,'') AS 'Inv_Code',
		ISNULL(Tax_Number,'') AS 'Tax_Number',
		ISNULL(Delivery_Address,'') AS 'Delivery_Address',
		ISNULL(Delivery_Suburb,'') AS 'Delivery_Suburb',
		ISNULL(Delivery_City,'') AS 'Delivery_City',
		ISNULL(Delivery_Post_Code,'') AS 'Delivery_Post_Code',		   
		AS_Transactions_Address_Detail_ID As 'ID'
	FROM AS_Transactions_Address_Detail				
	WHERE AC_Customers_ID = @AC_Customers_ID
	ORDER BY Customer_Name, Delivery_Address
GO

--67 Cursor_Update_Hist_Invoice_Address_Details
SET NOCOUNT ON
GO
DECLARE Get_Data CURSOR 
FOR
SELECT
	DISTINCT
	c.AC_Customers_ID,
	ISNULL(c.Surname,''),
	ISNULL(c.Firstnames,''),
	ISNULL(c.Street_Address,''),
	ISNULL(c.Suburb,''),
	ISNULL(c.City,''),
	ISNULL(c.Street_Post_Code,''),
	ISNULL(c.Post_Box,''),
	ISNULL(c.Post_Office,''),
	ISNULL(c.Post_Code,''),
	ISNULL(c.Tax_Number,'')
FROM AC_Customers c
	INNER JOIN AS_Transactions_Address_Detail d
		ON c.AC_Customers_ID = d.AC_Customers_ID
WHERE d.Customer_Name IS NULL		

DECLARE @AC_Customers_ID	Int,
		@Surname			Varchar(40),
		@Firstnames			Varchar(50),
		@Street_Address		Varchar(40),
		@Suburb				Varchar(30),
		@Street_Post_Code	Varchar(10),
		@Post_Box			Varchar(20),
		@Post_Office		Varchar(30),
		@City				Varchar(30),
		@Post_Code			Varchar(10),
		@Tax_Number			Varchar(16),
		
		@Postal_Address		Int,
		@Trading_Name		Int,
		@Customer_Name		Varchar(50)

	SET @Postal_Address = 0
	SET @Trading_Name = 0

	SELECT @Postal_Address = 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'optPOSPrintAddress'
	AND Control_Index = 0
	AND Control_Value = 'True'
	
	SELECT @Postal_Address = 0
	FROM Sys_AW_Options
	WHERE Control_Name = 'optPOSPrintAddress'
	AND Control_Index = 0
	AND Control_Value = 'False'
	
	SELECT @Trading_Name = 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkPOSPrintTradeName'
	AND Control_Index = 0
	AND Control_Value = 1

OPEN Get_Data
FETCH NEXT FROM Get_Data INTO @AC_Customers_ID, @Surname, @Firstnames, @Street_Address, @Suburb, @City, @Street_Post_Code,
						@Post_Box, @Post_Office, @Post_Code,	@Tax_Number
WHILE @@FETCH_STATUS = 0
BEGIN

	IF @Trading_Name = 1
	BEGIN
		SET @Customer_Name = LEFT(LTRIM(RTRIM(@Surname + ' / ' + @Firstnames)),50)
	END
	ELSE
	BEGIN
		SET @Customer_Name = LTRIM(RTRIM(@Surname))
	END						
						
	IF @Postal_Address = 1
	BEGIN
		UPDATE AS_Transactions_Address_Detail 
		SET AS_Transactions_Address_Detail.Inv_Address1 = @Post_Box,
			AS_Transactions_Address_Detail.Inv_Address2 = @Post_Office,
			AS_Transactions_Address_Detail.Inv_City = @City,
			AS_Transactions_Address_Detail.Inv_Code = @Post_Code,
			AS_Transactions_Address_Detail.Customer_Name = @Customer_Name,
			AS_Transactions_Address_Detail.Tax_Number = @Tax_Number,
			AW_YesNo_Invoice = 1			
		WHERE AC_Customers_ID = @AC_Customers_ID
		AND Customer_Name IS NULL	
	END
	ELSE
	BEGIN
		UPDATE AS_Transactions_Address_Detail 
		SET AS_Transactions_Address_Detail.Inv_Address1 = @Street_Address,
			AS_Transactions_Address_Detail.Inv_Address2 = @Suburb,
			AS_Transactions_Address_Detail.Inv_City = @City,
			AS_Transactions_Address_Detail.Inv_Code = @Street_Post_Code,
			AS_Transactions_Address_Detail.Customer_Name = @Customer_Name,
			AS_Transactions_Address_Detail.Tax_Number = @Tax_Number,
			AW_YesNo_Invoice = 1		
		WHERE AC_Customers_ID = @AC_Customers_ID
		AND Customer_Name IS NULL
	END					

	FETCH NEXT FROM Get_Data INTO @AC_Customers_ID, @Surname, @Firstnames, @Street_Address, @Suburb, @City, @Street_Post_Code,
							@Post_Box, @Post_Office, @Post_Code,	@Tax_Number
END
CLOSE Get_Data
DEALLOCATE Get_Data
GO

SET NOCOUNT OFF
GO

UPDATE AS_Transactions_Address_Detail
SET AW_YesNo_Delivery_Address = 1
WHERE (Delivery_Address <> ''
OR Delivery_Suburb <> ''
OR Delivery_City <> ''
OR Delivery_Post_Code <> '')
AND AW_YesNo_Delivery_Address IS NULL
GO

UPDATE AS_Transactions_Address_Detail
SET AW_YesNo_Delivery_Address = 0
WHERE AW_YesNo_Delivery_Address IS NULL
GO

--68 sp_AA_DB_Size_Ver
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AA_DB_Size_Ver]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AA_DB_Size_Ver]
GO
CREATE PROCEDURE [dbo].[sp_AA_DB_Size_Ver]
    (
            @DB_Name varchar(50),
            @Msg            varchar(500)    OUTPUT,
            @DB_Version     varchar(20)		OUTPUT
    )
AS

SET NOCOUNT ON

Declare @DB_Size        int

Set @Msg = ''

SELECT 
  @DB_Size = (size*8)/1024
FROM 
  sysfiles
WHERE 
  filename Like '%.mdf'

SELECT @DB_Version = Cast( SERVERPROPERTY('productversion') As Varchar)
--SELECT @DB_Size
If SUBSTRING(@DB_Version,1,2) = '8.' --2000
Begin
  If @DB_Size > 1700
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

If SUBSTRING(@DB_Version,1,2) = '9.' --2005
Begin
  If @DB_Size > 3400
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

If SUBSTRING(@DB_Version,1,2) = '10' --2008
Begin
  If SUBSTRING(@DB_Version,1,4) = '10.0'
  Begin
    If @DB_Size > 3400
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
  End
  
If SUBSTRING(@DB_Version,1,4) = '10.5'
  Begin
    If @DB_Size > 6800
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
  End
End

If SUBSTRING(@DB_Version,1,2) = '11' --2012
Begin
  If @DB_Size > 10200
      Set @Msg = 'Please Contact SpiralSoft. Your Database Size Has Almost Reached Its Limit. Version - ' + @DB_Version + ', Size - ' + Cast(@DB_Size As Varchar)
End

Select @Msg

SET NOCOUNT OFF
GO

--69 alt_AS_Transactions_Details TDHeader TDDetail
--Add Transaction Detail Header
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_Transaction_Details' AND
        C.Name='TDHeader'
) 
ALTER TABLE AS_Transaction_Details ADD TDHeader Varchar(256) NULL
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transaction_Details].[TDHeader]'
-------------------------------------------------------
GO
UPDATE AS_Transaction_Details
SET TDHeader = ''
WHERE TDHeader IS NULL	
GO

--Add Transaction Detail Detail
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_Transaction_Details' AND
        C.Name='TDDetail'
) 
ALTER TABLE AS_Transaction_Details ADD TDDetail Varchar(256) NULL
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transaction_Details].[TDDetail]'
-------------------------------------------------------
GO
UPDATE AS_Transaction_Details
SET TDDetail = ''
WHERE TDDetail IS NULL	
GO

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

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) = '',		
		@OldTransactionTypeID int = NULL,
		@TransactionTypeID int = NULL
    )
AS

SET NOCOUNT ON

	DECLARE @PromoSalesQty decimal(9,3)

-------------------------------------------------------------------------------
    --> Based on the TransactionType, determine where Qty is to be updated
-------------------------------------------------------------------------------
    --> Invoice
	IF @TransactionTypeID = 3
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate()
            WHERE AP_Products_ID = @ProductID
		END
	ELSE

    --> Refund
	IF @TransactionTypeID = 4
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty
            WHERE AP_Products_ID = @ProductID
		END
	ELSE

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

	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
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@Cost,
			@Price,
			@OriginalPrice,
			@Discount,
			@Tax,
			@TotalAmount,
			@Commission,
			@PromotionProductID,
            @JobRefID,
            @SerialNo,
            @Make,
            @Customer,
			@UserID,
			@CompanyID,
			ISNULL(@TDHeader,''),
			ISNULL(@TDDetail,'')
		)

	SELECT @DocumentDetailsID = Scope_Identity()



RETURN @DocumentDetailsID
Go

--71 sp_AS_POS_Transaction_Document_Details_Select
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Document_Details_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Details_Select]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Details_Select
--Purpose       :Selects POS transaction details for POS TALLY
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Detail_Insert
--              :       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    :The order of fields determine the order in the POS Tally grid
--Date          :2002/01/03
--Authors       :TB
--Version       :1.0.0
--MODS          :15/02/04 - Replaced d.Item_Number with NEW d.AP_Promotion_Products_ID
--              :26/02/04 - Replaced [ItemsNumber] with [PromotionProductID] that
--              :           caused an 'Cannot find item in collection' error when
--              :           extracting the Detail parameters in SpSPOSTrans.CDocument
--              :28/02/04 - Added [PromotionPrice] parameter
--              :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.7      :03/08/07 - Added [TaxRate] field
--              :05/08/07 - Changed ORDER of TALLY amount columns in SetGridWidths() to now
--              :           moved Unit Price ahead of Discount and Total
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    SELECT 
    	p.Description as [Description],
    	p.Product_Code as [Code], 
    	d.Quantity as [Qty], 
    	d.Unit_Price as [Price], 
    	d.Discount_Amount as [Discount], 
    	d.Extended_Amount as [TotalAmount], 
    	d.Unit_Cost as [Cost], 
    	d.Original_Price as [OriginalPrice], 
    	d.Tax_Amount as [Tax], 
    	d.Commission_Amount as [Commission], 
    	d.AP_Promotion_Products_ID as [PromotionProductID], 
    	d.Unit_Price as [PromotionPrice], 
    	d.AS_Job_References_ID as [JobRefID],
        d.Serial_No as [SerialNo],
        d.Make as [Make],
        d.Customer as [Customer],
    	d.Date_Captured as [DateCaptured], 
    	d.User_ID as [UserID], 
    	d.AW_User_Companies_ID as [CompanyID],
    	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
    	d.AS_Transactions_ID as [DocumentID], 
    	d.AP_Products_ID as [ProductID],
        t.Tax_Rate as [TaxRate],
        d.TDHeader as TDHeader,
        d.TDDetail as TDDetail

    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p 
    		ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Sys_AW_Tax_Codes t
            ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
    WHERE AS_Transactions_ID = @DocumentID
Go

--72 sp_AS_POS_Transaction_Document_Details_Select_Absolute
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Document_Details_Select_Absolute]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Details_Select_Absolute]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Transaction_Document_Details_Select_Absolute
--Purpose       :Loads RECALLed Transaction Details at POS
--Functionality :NB NB: The ALIAS in sp_AS_POS_Transaction_Document_Detail_Insert
--              :       MUST correspond to the INPUT PARAMETER NAMES BECAUSE
--              :       their values are ASSIGNED to each other after stripping the @
--              :       in POS TRANSACTION object's .Save()
--Peculiarity   :THE ORDER OF FIELDS DETERMINE THE ORDER IN THE POS TALLY GRID
--Date          :2002/01/05
--Authors       :TB
--MODS          :15/02/04 - Replaced d.Item_Number with NEW d.AP_Promotion_Products_ID
--              :26/02/04 - Replaced [ItemsNumber] with [PromotionProductID] that
--              :           caused an 'Cannot find item in collection' error when
--              :           extracting the Detail parameters in SpSPOSTrans.CDocument
--              :28/02/04 - Added [PromotionPrice] parameter
--              :22/05/04 - Added POS Document RECALL Product Re-Costing method
--              :08/01/05 - Added [JobRefID] for new AS_Job_References_ID field
--2004.3.2      :24/09/06 - Added @ActiveOnly to optionally recall ACTIVE products ONLY
--              :08/10/06 - Added [SerialNo] for new Serial_No field
--2004.3.4      :21/03/07 - Added [Make] and [Customer] fields
--2004.3.5      :13/05/07 - Added replace UNUSED (ABS(d.Commission_Amount) as [Commission])
--              :           on recalled Job Card and Sales Order transactions with
--              :           (ABS(d.Quantity) as [Commission]) using IMPLICIT CONVERSION
--              :           to enable identifying ITEMS as a RECALLED item in ExceedsOnHand()
--              :           using 'Include Qty Reserved on Job Cards in On Hand validation'
--2004.3.7      :03/08/07 - Added [TaxRate] field
--              :05/08/07 - Changed ORDER of TALLY amount columns in SetGridWidths() to now
--              :           moved Unit Price ahead of Discount and Total
--2004.4.0      :09/07/08 - Removed CONVERT numerics to ABS() if recalled document
--              :           is a JOBCARD or SALES ORDER (@ReserveTypeRecall = 1)
--              :14/08/08 - Commented CONVERT numerics to ABS() ONLY if recalled document
--              :           is a JOBCARD or SALES ORDER (@ReserveTypeRecall = 1)
--              :           This causes [Discount] in Tally to be NEGATIVE and the AMOUNT
--              :           value to be incorrect with DOUBLE the [Discount] amount
--              :03/09/08 - Added CONVERT [Discount] numerics to ABS() if recalled document
--              :           is a SALES ORDER (@ReserveTypeRecall = 1) to enable correct
--              :           recall of SALES ORDER VOLUME DISCOUNTS Tax amount
--2004.4.2      :30/11/08 - Removed @ReserveTypeRecall and replaced with @TranTypeID and added
--              :           seperate section for JOB CARD recalls and added assign QUANTITY
--              :           to the COMMISSION field as RESERVED !!!
--V6.0	RL	2014-07-17	:Added TDHeader and TDDetail
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON


    DECLARE @RecallCosting smallint,
            @CostingMethod smallint,
            @ActiveOnly varchar(10),
            @TranTypeID tinyint


    SET @RecallCosting = 0

    SELECT @RecallCosting = Control_Index
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optPOSRecallCosting' AND
          Control_Value = 'True'


    SET @CostingMethod = 0

    SELECT @CostingMethod = Control_Index
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True'


    SET @ActiveOnly = ''

    SELECT @ActiveOnly = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = 'CheckBox' AND
          Control_Name = 'chkRecallActiveOnly' AND
          Control_Index = 0


    ---------------------------------------------------------------------
    --> Set the Transaction Type ID of the RECALLED document if ACTIVE
    ---------------------------------------------------------------------
    SET @TranTypeID = 0


    SELECT @TranTypeID = ISNULL(Sys_AW_Transaction_Types_ID, 0)
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID AND
          Slu_AW_Active_ID = 1
    ---------------------------------------------------------------------


-------------------------------------------------------------------------------
-- IF Recalled document is a JOB CARD - Convert to ABS()
--    and assign its Quantity as [Commission]
-------------------------------------------------------------------------------
    IF @TranTypeID = 2        --JOB CARD
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END

-------------------------------------------------------------------------------
-- IF Recalled document is a SALES ORDER - DO NOT Convert to ABS()
--    and assign its Quantity as [Commission]
-------------------------------------------------------------------------------
    ELSE
    IF @TranTypeID = 16        --SALES ORDER
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ISNULL(p.Average_Cost, 0)
                                     WHEN @CostingMethod = 1
                                         THEN ISNULL(p.Last_Cost, 0)
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN d.Unit_Cost = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ISNULL(p.Average_Cost, 0)
                                             WHEN @CostingMethod = 1
                                                 THEN ISNULL(p.Last_Cost, 0)
                                             ELSE d.Unit_Cost
                                        END
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
--                            	d.Discount_Amount as [Discount], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ISNULL(p.Average_Cost, 0)
                                     WHEN @CostingMethod = 1
                                         THEN ISNULL(p.Last_Cost, 0)
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                
                                CASE WHEN d.Unit_Cost = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ISNULL(p.Average_Cost, 0)
                                             WHEN @CostingMethod = 1
                                                 THEN ISNULL(p.Last_Cost, 0)
                                             ELSE d.Unit_Cost
                                        END
                                     ELSE d.Unit_Cost
                                END as [Cost], 
                
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	d.Quantity as [Qty], 
                            	d.Unit_Price as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	d.Extended_Amount as [TotalAmount], 
                                d.Unit_Cost as [Cost], 
                            	d.Original_Price as [OriginalPrice], 
                            	d.Tax_Amount as [Tax], 
                                CONVERT(money, d.Quantity) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END
-------------------------------------------------------------------------------
-- IF Recalled document is a Quote, Invoice, Refund, Pro-Forma - Convert ABS()
--    and assign Commission_Amount as [Commission]
-- This section was how ALL documents were recallled prior to 2004.4.0
-------------------------------------------------------------------------------
    ELSE
        BEGIN
            IF @ActiveOnly = '1'        --Recall only Products that are currently set as ACTIVE
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID AND
                                  p.Slu_AW_Active_ID = 1
                        END
                END
            ELSE                        --Recall ALL Products (ignore Slu_AW_Active_ID)
                BEGIN
                    IF @RecallCosting = 0        --RETAIN the Cost when created
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 1        --Re-Cost EACH Product when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN @CostingMethod = 0
                                         THEN ABS(ISNULL(p.Average_Cost, 0))
                                     WHEN @CostingMethod = 1
                                         THEN ABS(ISNULL(p.Last_Cost, 0))
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
                       			d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                    IF @RecallCosting = 2        --Re-Cost ONLY ZERO COST Products when recalled
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price], 
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                
                                CASE WHEN ABS(d.Unit_Cost) = 0
                                     THEN
                                        CASE WHEN @CostingMethod = 0
                                                 THEN ABS(ISNULL(p.Average_Cost, 0))
                                             WHEN @CostingMethod = 1
                                                 THEN ABS(ISNULL(p.Last_Cost, 0))
                                             ELSE ABS(d.Unit_Cost)
                                        END
                                     ELSE ABS(d.Unit_Cost)
                                END as [Cost], 
                
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                
                    ELSE
                        BEGIN
                            SELECT 
                            	p.Description as [Description],
                            	p.Product_Code as [Code], 
                            	ABS(d.Quantity) as [Qty], 
                            	ABS(d.Unit_Price) as [Price],
                            	ABS(d.Discount_Amount) as [Discount], 
                            	ABS(d.Extended_Amount) as [TotalAmount], 
                                ABS(d.Unit_Cost) as [Cost], 
                            	ABS(d.Original_Price) as [OriginalPrice], 
                            	ABS(d.Tax_Amount) as [Tax], 
                                ABS(d.Commission_Amount) as [Commission],
                            	d.AP_Promotion_Products_ID as [PromotionProductID], 
                            	d.Unit_Price as [PromotionPrice], 
                    	        d.AS_Job_References_ID as [JobRefID],
                                d.Serial_No as [SerialNo],
                                d.Make as [Make],
                                d.Customer as [Customer],
                            	d.Date_Captured as [DateCaptured], 
                            	d.User_ID as [UserID], 
                            	d.AW_User_Companies_ID as [CompanyID],
                            	d.AS_Transaction_Details_ID as [DocumentDetailsID], 
                            	d.AS_Transactions_ID as [DocumentID], 
                            	d.AP_Products_ID as [ProductID],
                                t.Tax_Rate as [TaxRate],
								d.TDHeader as TDHeader,
						        d.TDDetail as TDDetail                                
                            FROM AS_Transaction_Details d
                                LEFT JOIN AP_Products p 
                                    ON d.AP_Products_ID = p.AP_Products_ID
                        		LEFT JOIN Sys_AW_Tax_Codes t
                                    ON p.Sys_AW_Tax_Codes_ID = t.Sys_AW_Tax_Codes_ID
                            WHERE AS_Transactions_ID = @DocumentID
                        END
                END
        END






SET NOCOUNT OFF
Go

--73 sp_AO_Transaction_DocNo_Update
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Transaction_DocNo_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Transaction_DocNo_Update]
GO
-------------------------------------------------------------------------------
--Description	:sp_AO_Transaction_DocNo_Update
--Purpose       :UPDATE AS_Transactions.Payment_Amount
--Date			:2014/07/24
--Authors		:RL
--MODS    		:
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Transaction_DocNo_Update]
	(
		@TransactionID		int,
        @Document_Number	varchar(20)
	)
AS

SET NOCOUNT ON

	UPDATE AO_Transactions
    SET Document_Number = @Document_Number
    WHERE AO_Transactions_ID = @TransactionID

SET NOCOUNT OFF
GO

--74 sp_AC_Customer_Ageing_Select_All_Detail
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Ageing_Select_All_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Ageing_Select_All_Detail]
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Ageing_Select_All_Detail
--Purpose       :Retrieve Customer Ageing With Customer Details
--              :Age Areas are Current to 180+ days
--Parameters    :
--Date          :2014/08/12
--Authors       :RL
------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Customer_Ageing_Select_All_Detail]
	(
        @CompanyID int
    )
AS

SET NOCOUNT ON

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

	SET @Now = getdate()

--> Retrieves last (up to) 7 Month-Ends DATES
	EXEC sp_AW_Period_Procedures_Select
        @Now,
        @D1 OUTPUT,
        @D2 OUTPUT,
        @D3 OUTPUT,
        @D4 OUTPUT,
        @D5 OUTPUT,
        @D6 OUTPUT,
        @D7 OUTPUT,
        1,
        @CompanyID

	SELECT 
    c.AC_Customers_ID AS [ID], 
	ISNULL(c.Customer_Number,'') AS [Customer No], 
	ISNULL(c.Surname,'') AS [Name], 
	ISNULL(c.Firstnames,'') AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	ISNULL(c.Initials,'') AS [Initials], 
	ISNULL(l.[Description],'') AS [Language], 
	ISNULL(c.IDReg_Number,'') AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	ISNULL(a.[Description],'') AS [Active], 
	ISNULL(s.[Description],'') AS [Account Status],
	ISNULL(c.Contact_Name,'') AS [Contact Name], 
	ISNULL(r.[Description],'') AS [Salesperson],
	ISNULL(c.Post_Box,'') AS [Post Box], 
	ISNULL(c.Post_Office,'') AS [Post Office], 
	ISNULL(c.Post_Code,'') AS [Post Code], 
	ISNULL(c.Street_Address,'') AS [Street Address], 
	ISNULL(c.Suburb,'') AS [Suburb], 
	ISNULL(c.City,'') AS [City], 
	ISNULL(c.Street_Post_Code,'') AS [Street Code], 
	ISNULL(cu.[Description],'') + ' (' + ISNULL(cu.Country_Code3,'') + ')' AS [Country], 
	ISNULL(c.Delivery_Address,'') AS [Delivery Address], 
	ISNULL(c.Delivery_Suburb,'') AS [Delivery Suburb], 
	ISNULL(c.Delivery_City,'') AS [Delivery City], 
	ISNULL(c.Delivery_Post_Code,'') AS [Delivery Post Code], 
	ISNULL(c.Web_Site_URL,'') AS [Web Site URL], 
	ISNULL(c.Orders_URL,'') AS [Order URL], 
	ISNULL(c.Home_Email,'') AS [E-mail Home], 
	ISNULL(c.Work_Email,'') AS [E-mail Work],
	ISNULL(c.Home_Tel_No,'') AS [Home Tel No], 
	ISNULL(c.Work_Tel_No,'') AS [Work Tel No], 
	ISNULL(c.Cell_No,'') AS [Cell No], 
	ISNULL(c.Fax_No,'') AS [Fax No], 
	ISNULL(dc.[Description],'') AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ISNULL(ct.[Description],'') AS [Credit Terms],
	ISNULL(c.Credit_Insurers_Reference,'') AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ISNULL(ci.[Description],'') AS [Charge Interest],
	ISNULL(sa.[Description],'') AS [Sales Area], 
	ISNULL(c.Head_Office,'') AS [Head Office], 
	ISNULL(ct.[Description],'') AS [Customer Type], 
	ISNULL(tc.[Description],'') AS [Tax Code], 
	ISNULL(c.Tax_Number,'') AS [Tax Number],
	ISNULL(act.[Description],'') AS [Account Types],
	ISNULL(ctt.[Description],'') AS [Credit Term Types],
	ISNULL(c.Notes,'') AS [Notes],
	ISNULL(x.Amount,0) AS Amount,
	ISNULL(x.Payment,0) As Payment, 
	ISNULL(x.[Current],0) AS [Current], 
	ISNULL(x.[30 Days],0) AS [30 Days], 
	ISNULL(x.[60 Days],0) AS [60 Days], 
	ISNULL(x.[90 Days],0) AS [90 Days], 
	ISNULL(x.[120 Days],0) As [120 Days],
	ISNULL(x.[150 Days],0) As [150 Days],
	ISNULL(x.[180+ Days],0) AS [180+ Days]
	FROM fn_AC_Customer_Ageing_Grouped_All_Customers
        (
            @Now,
            @D1,
            @D2,
            @D3,
            @D4,
            @D5,
            @D6,
            @D7
        ) x
        RIGHT OUTER JOIN AC_Customers c
			On c.AC_Customers_ID = x.CustomerID
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID			 

SET NOCOUNT OFF
GO

--75 sp_AP_Insert_New_Price_Update_Product
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Insert_New_Price_Update_Product]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Insert_New_Price_Update_Product]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_New_Price_Update_Product
--Purpose       :Inserts NEW AP_Products from unmatched Price Update data
--Parameters    :
--Date          :2004/04/19
--Authors       :TB
--Version       :1.0.0
--MODS          :18/06/04 - Added @LastCost input parameter
--              :05/04/05 - Added @ManufacturerID input parameter
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_New_Price_Update_Product]
	(
        @ProductCode varchar(20),
        @ProductDesc varchar(50),
        @Price1EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ManufacturerID int,
        @UserID int
	)
AS     

SET NOCOUNT ON

    INSERT AP_Products
        (
            [Description],
            Print_Description,
            Product_Code,
            SKU_Code,
            Lup_AP_Product_Manufacturers_ID,
            Manufacturer_Code,
            Manufacturer_Description,
            Default_Supplier_ID,
            Lup_AP_Product_Types_ID,
            Lup_AP_Product_Groups_ID,
            Lup_AP_Product_Departments_ID,
            Last_Cost,
            Average_Cost,
            Price1_Effective_Date,
            Price1_Price1,
            Price1_Price2,
            [User_ID]
        )
    VALUES
        (
            LEFT(@ProductDesc, 50),
            LEFT(@ProductDesc, 30),
            @ProductCode,
            @ProductCode,
            @ManufacturerID,
            @ProductCode,
            LEFT(@ProductDesc, 50),
            1,
            1,
            1,
            1,
            @LastCost,
            0,
            @Price1EffectiveDate,
            @Price1,
            @Price2,
            @UserID
        )


SET NOCOUNT OFF
GO

--76 sp_AP_Delete_Inactive_Product
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_Inactive_Product]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_Inactive_Product]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Inactive_Product
--Purpose       :DELETE ONE Redundant UNUSED Product with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE, GRV, ORDER, ADJUSTMENT exists and
--              :        Product has ZERO ON HAND
--Date          :2008/05/19
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Inactive_Product]
	(
		@ProductID int,
        @ActivityCNT tinyint,
        @OnHand decimal(9, 3),
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @ReturnCode		int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)

    SET @ReturnCode = 0


    --> If ZERO Sale, GRV, Order, Adjustment rows AND On_Hand
    IF @ActivityCNT = 0 AND @OnHand = 0

        BEGIN

            --> Apart from Sale, GRV, Order, and Adjustment tables
            --> DELETE Product in OTHER RELATED tables
            BEGIN TRAN Delete_Product
        
            	BEGIN
        
					SELECT	@Product_Code = ISNULL(Product_Code,''),
							@Description = ISNULL([Description],'')
					FROM AP_Products
					WHERE AP_Products_ID = @ProductID
        
                    DELETE AO_Order_Candidates
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Order_Candidates_Temp
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Supplier_Contracts
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AO_Supplier_Product_Discounts
                    WHERE AP_Products_ID = @ProductID
        
                    DELETE AP_Inventory_Adjustments
                    WHERE AP_Products_ID = @ProductID
        
                    DELETE AP_Product_Selling_Prices
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Assemblies
                    WHERE AP_Parent_Product_ID = @ProductID OR
                          AP_Child_Product_ID = @ProductID
                
                    DELETE AP_Products_History
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Stock_Takes
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Suppliers
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Products_Switch3
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Promotion_Products
                    WHERE AP_Products_ID = @ProductID
                
                    DELETE AP_Stock_Exchange
                    WHERE AP_Products_ID = @ProductID
                
                
                    --> NOW delete Product
                    DELETE AP_Products
                    WHERE AP_Products_ID = @ProductID
                
					INSERT INTO AP_Products_Audit
					(
						Record_Action, 
						Action_Date, 
						[User_ID],
						AP_Products_ID, 
						Field, 
						Prev_Value, 
						New_Value
					)
					VALUES
					(
						'Delete', 
						GetDate(), 
						@UserID,
						@ProductID, 
						'', 
						@Product_Code,
						@Description
					)
                
                    SET @ReturnCode = 1
        
                END

            COMMIT TRAN Delete_Product

        END

RETURN @ReturnCode
GO

--77 sp_AP_Update_Product_Selling_Price_History
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_Selling_Price_History]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_Selling_Price_History]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Selling_Price_History
--Purpose       :select's a specific products Selling price history 
--Functionality :
--Parameters    : 
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Product_Selling_Price_History]
    (
        @Product_ID int,
        @New_Price1_Effective_Date datetime,
        @New_Price1_Price1 money,
        @New_Price1_Price2 money,
        @New_Price2_Effective_Date datetime,
        @New_Price2_Price1 money,
        @New_Price2_Price2 money,
        @User_ID int,
        @Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Price1_Effective_Date datetime,	
    		@Prev_Price1_Price1 money,
    		@Prev_Price1_Price2 money,
    		@Prev_Price2_Effective_Date datetime,
    		@Prev_Price2_Price1 money,
    		@Prev_Price2_Price2 money,
    		@Stock_On_Hand Decimal(9,3)
    
    BEGIN
        BEGIN
			SELECT
                @Stock_On_Hand = On_Hand,
                @Prev_Price1_Effective_Date = Price1_Effective_Date,
                @Prev_Price1_Price1 = Price1_Price1,
                @Prev_Price1_Price2 = Price1_Price2,
                @Prev_Price2_Effective_Date = Price2_Effective_Date,
                @Prev_Price2_Price1 = Price2_Price1,
                @Prev_Price2_Price2 = Price2_Price2
			FROM AP_Products 
			WHERE AP_Products_ID = @Product_ID AND
                  AW_User_Companies_ID = @Company_ID
        END 
    
		BEGIN
            INSERT INTO AP_Product_Selling_Prices
                (		
                    AP_Products_ID ,
                    On_Hand ,
                    Prev_Price1_Effective_Date ,
                    Prev_Price1_Price1 ,
                    Prev_Price1_Price2 ,
                    Prev_Price2_Effective_Date ,
                    Prev_Price2_Price1 ,	
                    Prev_Price2_Price2 ,
                    New_Price1_Effective_Date ,
                    New_Price1_Price1 ,
                    New_Price1_Price2 ,
                    New_Price2_Effective_Date ,
                    New_Price2_Price1 ,	
                    New_Price2_Price2 ,
                    Date_Captured ,
                    [User_ID] , 
                    AW_User_Companies_ID
                ) 
			VALUES
                (
                    @Product_ID,
                    @Stock_On_Hand,
                    @Prev_Price1_Effective_Date,
                    @Prev_Price1_Price1,
                    @Prev_Price1_Price2,
                    @Prev_Price2_Effective_Date,
                    @Prev_Price2_Price1,
                    @Prev_Price2_Price2,
                    @New_Price1_Effective_Date,
                    @New_Price1_Price1,
                    @New_Price1_Price2,
                    @New_Price2_Effective_Date,
                    @New_Price2_Price1,
                    @New_Price2_Price2,
                    getdate(),
                    @User_ID,
                    @Company_ID
                )
		END
    
		BEGIN	
			UPDATE AP_Products 
			SET Price1_Effective_Date = @New_Price1_Effective_Date,
				Price1_Price1 = @New_Price1_Price1,
				Price1_Price2 = @New_Price1_Price2,
				Price2_Effective_Date = @New_Price2_Effective_Date,
				Price2_Price1 = @New_Price2_Price1,
				Price2_Price2 = @New_Price2_Price2,
				[User_ID] = @User_ID
			WHERE AP_Products_ID = @Product_ID AND
                  AW_User_Companies_ID = @Company_ID
		END
    END

SET NOCOUNT OFF
GO

--78 sp_AP_Delete_Redundant_ProductID
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_Redundant_ProductID]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_Redundant_ProductID]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Redundant_ProductID
--Purpose       :DELETE Redundant UNUSED ProductID with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Redundant_Products
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Redundant_ProductID]
	(
        @ProductID	int,
        @UserID		int
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)


    SET @RetCode = 0

        
		SELECT	@Product_Code = ISNULL(Product_Code,''),
				@Description = ISNULL([Description],'')
		FROM AP_Products
		WHERE AP_Products_ID = @ProductID

        --> DELETE Product in RELATED tables
        DELETE AO_Order_Candidates
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Order_Candidates_Temp
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Contracts
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Product_Discounts
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Product_Selling_Prices
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Assemblies
        WHERE AP_Parent_Product_ID = @ProductID OR
              AP_Child_Product_ID = @ProductID

        DELETE AP_Products_History
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Stock_Takes
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Suppliers
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Switch3
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Promotion_Products
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Stock_Exchange
        WHERE AP_Products_ID = @ProductID


        --> NOW delete Product
        DELETE AP_Products
        WHERE AP_Products_ID = @ProductID

		INSERT INTO AP_Products_Audit
		(
			Record_Action, 
			Action_Date, 
			[User_ID],
			AP_Products_ID, 
			Field, 
			Prev_Value, 
			New_Value
		)
		VALUES
		(
			'Delete', 
			GetDate(), 
			@UserID,
			@ProductID, 
			'', 
			@Product_Code,
			@Description
		)

    SET @RetCode = 1

RETURN @RetCode
GO

--79 sp_AP_Delete_Disabled_ProductID
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_Disabled_ProductID]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_Disabled_ProductID]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Disabled_ProductID
--Purpose       :Delete UNUSED DISABLED Products in local DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Disabled_Products
--Date          :2008/08/01
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Disabled_ProductID]
	(
        @ProductID	int,
        @UserID		int        
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)


    SET @RetCode = 0

		SELECT	@Product_Code = ISNULL(Product_Code,''),
				@Description = ISNULL([Description],'')
		FROM AP_Products
		WHERE AP_Products_ID = @ProductID

        --> DELETE Product in RELATED tables
        DELETE AO_Order_Candidates
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Order_Candidates_Temp
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Contracts
        WHERE AP_Products_ID = @ProductID

        DELETE AO_Supplier_Product_Discounts
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Product_Selling_Prices
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Assemblies
        WHERE AP_Parent_Product_ID = @ProductID OR
              AP_Child_Product_ID = @ProductID

        DELETE AP_Products_History
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Stock_Takes
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Suppliers
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Products_Switch3
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Promotion_Products
        WHERE AP_Products_ID = @ProductID

        DELETE AP_Stock_Exchange
        WHERE AP_Products_ID = @ProductID


        --> NOW delete Product
        DELETE AP_Products
        WHERE AP_Products_ID = @ProductID

		INSERT INTO AP_Products_Audit
		(
			Record_Action, 
			Action_Date, 
			[User_ID],
			AP_Products_ID, 
			Field, 
			Prev_Value, 
			New_Value
		)
		VALUES
		(
			'Delete', 
			GetDate(), 
			@UserID,
			@ProductID, 
			'', 
			@Product_Code,
			@Description
		)

    SET @RetCode = 1

RETURN @RetCode
GO

--80 sp_AP_Update_Null_Product_Codes
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Null_Product_Codes]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Null_Product_Codes]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Null_Product_Codes
--Purpose       :Product Updates - Set NULL Product Codes
--Date          :2008/07/19
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    UPDATE AP_Products
    SET Product_Code = 'Null',
		[User_ID] = @UserID
    WHERE AW_User_Companies_ID = @CompanyID AND
          (Product_Code IS NULL OR
           RTRIM(LTRIM(Product_Code)) = '')


    SET @ReturnValue = 1

RETURN @ReturnValue
GO

--81 sp_AP_Delete_Duplicate_Product_Code
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_Duplicate_Product_Code]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_Duplicate_Product_Code]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_Duplicate_Product_Code
--Purpose       :DELETE DUPLICATE ProductID with ZERO STOCK in target DB
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Companion SP  :sp_AP_Select_Duplicate_Product_Codes
--Date          :2007/05/03
--Authors       :TB
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_Duplicate_Product_Code]
	(
        @ProductCode varchar(20),
        @CompanyID int,
        @UserID		int
	)
AS

SET NOCOUNT ON

	DECLARE @ProductID int,
            @DeleteCNT int
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)           


    SET @DeleteCNT = 0


	DECLARE Delete_Dups CURSOR FOR
        (
            SELECT a.AP_Products_ID
            FROM AP_Products a
                FULL OUTER JOIN AS_Transaction_Details b
                    ON a.AP_Products_ID = b.AP_Products_ID
                FULL OUTER JOIN AO_GRV_Details c
                    ON a.AP_Products_ID = c.AP_Products_ID
                FULL OUTER JOIN AO_Order_Details d
                    ON a.AP_Products_ID = c.AP_Products_ID
            WHERE b.AP_Products_ID IS NULL AND
                  c.AP_Products_ID IS NULL AND
                  d.AP_Products_ID IS NULL AND
                  a.AW_User_Companies_ID = @CompanyID AND
                  a.Product_Code = @ProductCode AND
                  a.On_Hand = 0
        )

	OPEN Delete_Dups

    	FETCH NEXT FROM Delete_Dups 
    	INTO
            @ProductID
    	
    	WHILE @@FETCH_STATUS = 0
    	BEGIN

			SELECT	@Product_Code = ISNULL(Product_Code,''),
					@Description = ISNULL([Description],'')
			FROM AP_Products
			WHERE AP_Products_ID = @ProductID

            --> DELETE Product in RELATED tables
            DELETE AO_Order_Candidates
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Order_Candidates_Temp
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Supplier_Contracts
            WHERE AP_Products_ID = @ProductID

            DELETE AO_Supplier_Product_Discounts
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Inventory_Adjustments
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Product_Selling_Prices
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Assemblies
            WHERE AP_Parent_Product_ID = @ProductID OR
                  AP_Child_Product_ID = @ProductID

            DELETE AP_Products_History
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Stock_Takes
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Suppliers
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Products_Switch3
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Promotion_Products
            WHERE AP_Products_ID = @ProductID

            DELETE AP_Stock_Exchange
            WHERE AP_Products_ID = @ProductID


            --> NOW delete Product
            DELETE AP_Products
            WHERE AP_Products_ID = @ProductID

			INSERT INTO AP_Products_Audit
			(
				Record_Action, 
				Action_Date, 
				[User_ID],
				AP_Products_ID, 
				Field, 
				Prev_Value, 
				New_Value
			)
			VALUES
			(
				'Delete', 
				GetDate(), 
				@UserID,
				@ProductID, 
				'', 
				@Product_Code,
				@Description
			)

            SET @DeleteCNT = @DeleteCNT + 1


        	FETCH NEXT FROM Delete_Dups 
        	INTO
                @ProductID

    	END

	CLOSE Delete_Dups

	DEALLOCATE Delete_Dups

RETURN @DeleteCNT
GO

--82 sp_AP_Delete_NonActive_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_NonActive_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_NonActive_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_NonActive_Products
--Purpose       :DELETE NON Active UNUSED Products with ZERO STOCK
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Date          :2013/07/23
--Authors       :RL
--MODS:         :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Delete_NonActive_Products]
	(
        @ProductID	int,
        @CompanyID	int,
        @UserID		int
	)
AS

SET NOCOUNT ON

	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)

IF EXISTS
(
	SELECT a.AP_Products_ID
	FROM AP_Products a
	FULL OUTER JOIN AS_Transaction_Details b
		ON a.AP_Products_ID = b.AP_Products_ID
	FULL OUTER JOIN AO_GRV_Details c
		ON a.AP_Products_ID = c.AP_Products_ID
	FULL OUTER JOIN AO_Order_Details d
		ON a.AP_Products_ID = c.AP_Products_ID
	WHERE	a.AP_Products_ID = @ProductID AND
			a.AW_User_Companies_ID = @CompanyID AND
			a.Slu_AW_Active_ID <> 1 AND
			b.AP_Products_ID IS NULL AND
			c.AP_Products_ID IS NULL AND
			d.AP_Products_ID IS NULL AND
			a.On_Hand = 0 AND
			a.AP_Products_ID NOT IN (SELECT ISNULL(Levy_AP_Product_ID,0) FROM AP_Products)
)
BEGIN

	SELECT	@Product_Code = ISNULL(Product_Code,''),
			@Description = ISNULL([Description],'')
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID

	--> DELETE Product in RELATED tables
	DELETE AO_Order_Candidates
	WHERE AP_Products_ID = @ProductID

	DELETE AO_Order_Candidates_Temp
	WHERE AP_Products_ID = @ProductID

	DELETE AO_Supplier_Contracts
	WHERE AP_Products_ID = @ProductID

	DELETE AO_Supplier_Product_Discounts
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Inventory_Adjustments
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Product_Selling_Prices
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Assemblies
	WHERE AP_Parent_Product_ID = @ProductID OR
		AP_Child_Product_ID = @ProductID

	DELETE AP_Products_History
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Stock_Takes
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Suppliers
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Switch3
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Promotion_Products
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Stock_Exchange
	WHERE AP_Products_ID = @ProductID


	--> NOW delete Product
	DELETE AP_Products
	WHERE AP_Products_ID = @ProductID

	INSERT INTO AP_Products_Audit
	(
		Record_Action, 
		Action_Date, 
		[User_ID],
		AP_Products_ID, 
		Field, 
		Prev_Value, 
		New_Value
	)
	VALUES
	(
		'Delete', 
		GetDate(), 
		@UserID,
		@ProductID, 
		'', 
		@Product_Code,
		@Description
	)

END

SET NOCOUNT OFF
GO

--83 sp_AP_Insert_Price_Update
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Insert_Price_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Insert_Price_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Price_Update
--Purpose       :Updates AP_Products with Price Update data
--Parameters    :
--Date          :2003/12/31
--Authors       :TB
--Version       :1.0.0
--MODS          :18/06/04 - Added @LastCost input parameter
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Insert_Price_Update]
	(
        @ProductID int,
        @EffectiveDate datetime,
        @Price1 money,
        @Price2 money,
        @LastCost money,
        @ChkReplaceCost int,
        @UserID		int
	)
AS     

SET NOCOUNT ON

    DECLARE @Price1EffectiveDate datetime,
            @Price1Price1 money,
            @Price1Price2 money,
            @Price2EffectiveDate datetime,
            @Price2Price1 money,
            @Price2Price2 money
	DECLARE @Product_Code	varchar(20)
	DECLARE @Description	varchar(50)           

    SELECT @Price1EffectiveDate = Price1_Effective_Date,
           @Price1Price1 = Price1_Price1,
           @Price1Price2 = Price1_Price2,
           @Price2EffectiveDate = Price2_Effective_Date,
           @Price2Price1 = Price2_Price1,
           @Price2Price2 = Price2_Price2,
           @Product_Code = ISNULL(Product_Code,''),
		   @Description = ISNULL([Description],'')
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID

    --> If Price1 is OLDEST price
    --IF @Price1EffectiveDate <= @Price2EffectiveDate
    --RL 2014-10-15 Added ISNULL check. Need to test
	IF @Price1EffectiveDate <= ISNULL(@Price2EffectiveDate,'1900-01-01')
        BEGIN
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> If Price2 is OLDEST price
    ELSE
    --IF @Price2EffectiveDate <= @Price1EffectiveDate
    --RL 2014-10-15 Added ISNULL check. Need to test
    IF ISNULL(@Price2EffectiveDate,'1900-01-01') <= @Price1EffectiveDate
        BEGIN
            --> Move Price1 to Price2
        	UPDATE AP_Products
            SET Price2_Effective_Date = @Price1EffectiveDate,
                Price2_Price1 = @Price1Price1,
                Price2_Price2 = @Price1Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID

            --> Put NEW prices into Price1
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> If Price1 = Price2 and both dates are probably NULL
    ELSE
        BEGIN
            --> Put NEW prices into Price1
        	UPDATE AP_Products
            SET Price1_Effective_Date = @EffectiveDate,
                Price1_Price1 = @Price1,
                Price1_Price2 = @Price2,
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

    --> Replace Last Cost with the Cost in list (18/06/04)
    IF @ChkReplaceCost = 1
        BEGIN
        	UPDATE AP_Products
            SET Last_Cost = @LastCost,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
        END

SET NOCOUNT OFF
GO

--84 sp_AP_Update_Adjusted_Inventory_Details_Split_Types
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Adjusted_Inventory_Details_Split_Types]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Adjusted_Inventory_Details_Split_Types]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Adjusted_Inventory_Details_Split_Types
--Purpose       :Inserts SPLIT Stock Adjustments by PRODUCT TYPE and UPDATE GL
--              :    1. Inventory Control or
--              :    2. Split Inventory Control by PRODUCT TYPE if parameter is set
--              :
--   			:NB: Any mods must sync with sp_AP_Update_Inventory_Details
--              :    that is used for Goods Received and Returned Vouchers (GRV)
--Functionality :Handles Stock Adjustment Types 1, 3, 6
--Date          :2009/02/12
--Authors       :TB
--Mods          :
--2004.4.5      :15/07/09 - Reworked update General Ledger with the value of Stock Adjustments.
--              :           Previous Qty Adjustment was NOT inserted in GL if Costs not also adjusted
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.0      :06/04/11 - Moved SELECT @User_Name outside 'If Adjustment has AN INVENTORY VALUE ...' section
--V6.0	RL	2014-09-01	:Added Product audit trail info
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Adjusted_Inventory_Details_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
        	@Prev_On_Hand decimal(9,3),
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @Prev_Average_Cost money,
            @Prev_Average_On_Hand_Value money,
            @New_Average_On_Hand_Value money,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount int,
            @Diff_On_Hand decimal(9,3),
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @SplitGRVparameter varchar(10),
            @SplitGRVTypes int,
            @TypeDescription varchar(50),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 1            --Intialize as 'Adjustment' type
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    --> Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


    --> Get the CURRENT Product values
	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
		   @Prev_On_Hand = ISNULL(On_Hand, 0),
		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
    	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
           @Prev_Average_Cost = ISNULL(Average_Cost, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = @New_On_Hand,
        Job_Reserved = @New_Job_Reserved,
        Sales_Order_Reserved = @New_Sales_Order_Reserved,
        Quote_Reserved = @New_Quote_Reserved,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Average_Cost <> @New_Average_Cost OR
       @Prev_On_Hand <> @New_On_Hand
		BEGIN 
            -------------------------------------------------------
            --> Get Split GRV Stock Receipts to GL INVENTORY accounts parameter
            -------------------------------------------------------
            SET @SplitGRVparameter = '0'

            SELECT @SplitGRVparameter = Control_Value
            FROM Sys_AW_Options
            WHERE Control_Type = 'CheckBox' AND
                  Control_Name = 'chkUseProductPurchasesGL' AND
                  Control_Index = 0 AND
                  AW_User_Companies_ID = @CompanyID


            -------------------------------------------------------
            --> ONLY set @SplitGRVTypes if @SplitGRVparameter = '1'
            -------------------------------------------------------
            SET @SplitGRVTypes = 0

            IF @SplitGRVparameter = '1'
                BEGIN
                    SET @SplitGRVTypes = 1
                END
            -------------------------------------------------------


            -------------------------------------------------------
            --> Get the INVENTORY CONTROL if NOT Split GRV Stock Receipts parameter
            -------------------------------------------------------
            --> Update INVENTORY CONTROL
            SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 601        --Inventory Control
            -------------------------------------------------------


            ------------------------------------------------------------
            --> CALC Inventory Value Increase/Decrease
            ------------------------------------------------------------
            SET @Diff_On_Hand = 0
            SET @Diff_Value = 0

            ------------------------------------------------------------
            --> Assign Qty Adjustment Type
            ------------------------------------------------------------
            IF @Prev_On_Hand <> @New_On_Hand
                BEGIN
                    SET @Diff_On_Hand = @New_On_Hand - @Prev_On_Hand

                    SET @AdjustmentType = 1        --QTY Adjustment ONLY
                END

            ------------------------------------------------------------
            --> IF NOT Qty Adjustment then USE Previous On_Hand
            ------------------------------------------------------------
            IF @Diff_On_Hand = 0
                BEGIN
                    SET @Diff_On_Hand = @Prev_On_Hand
                END

            ------------------------------------------------------------
            --> Assign Reval/Deval Adjustment Type
            ------------------------------------------------------------
            IF @Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost
                BEGIN
                    SET @AdjustmentType = 3        --COST Adjustment ONLY
                END

            ------------------------------------------------------------
            --> Assign Stock Take-On Adjustment Type
            ------------------------------------------------------------
    		IF @Prev_On_Hand <> @New_On_Hand AND
              (@Prev_Last_Cost <> @New_Last_Cost OR
               @Prev_Average_Cost <> @New_Average_Cost)
    			BEGIN
                    SET @AdjustmentType = 6       --QTY AND COST Adjustment
                END


            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            IF @AdjustmentType = 1        --QTY Adjustment ONLY (@Diff_*_Cost = 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Qty by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Average_Cost), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * @Prev_Last_Cost), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 3        --COST Adjustment ONLY (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Costs by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Average_Cost - @Prev_Average_Cost)), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                            SET @Diff_Value = ROUND((@Diff_On_Hand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                        END
                END
            ELSE
            IF @AdjustmentType = 6        --QTY AND COST Adjustment (Stock Take-On) (@Diff_*_Cost <> 0)
                BEGIN
                    SET @Narration = 'Stock Adjust Take-On by '

                    IF @ValuationMethod = 0        -- Average Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Average_Cost * @Prev_On_Hand), 2)
                        END
                    ELSE                           -- Last Cost
                        BEGIN
                           SET @Diff_Value = ROUND((@New_Average_Cost * @New_On_Hand) - (@Prev_Last_Cost * @Prev_On_Hand), 2)
                        END
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> NEW 2004.4.3 - Get the Product TYPE Description
            ------------------------------------------------------------------------------
            SET @TypeDescription = ''

			SELECT @TypeDescription = ISNULL(t.Description, '')
			FROM AP_Products p
                LEFT JOIN Lup_AP_Product_Types t
                    ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
			WHERE p.AP_Products_ID = @ProductID


            SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)


            ------------------------------------------------------------------------------
            --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    ---------------------------------------------------------------------
                    --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                    ---------------------------------------------------------------------
                    SET @GLAdjustID = 0

                    SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @AdjustGLDescription AND
                          Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                          Slu_AW_Active_ID = 1


                    IF @GLAdjustID = 0
                        BEGIN
             				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                    @AdjustGLDescription,
                                                    14,
                                                    @UserID,
                                                    @CompanyID
                        END


                    ---------------------------------------------------------------------
                    --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                    ---------------------------------------------------------------------
                    IF @SplitGRVTypes = 1
                        BEGIN
                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                  Slu_AW_Active_ID = 1


                            IF @GLInventoryID = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
                            ---------------------------------------------------------------------
                        END
                    ---------------------------------------------------------------------


                --> Create NORMAL JOURNAL header for ADJUSTMENT
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    IF @SplitGRVTypes = 1
                        BEGIN
                        --> Create JOURNAL DETAIL for Inventory Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran


                        --> Create GL TRANSACTION for SPLIT GL Inventory Account
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLInventoryID,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END
                    ELSE
                        BEGIN
                        --> Create JOURNAL DETAIL for Inventory Control 601
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                        --> Create GL TRANSACTION for Inventory Control 601
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLControlAccount,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END


                --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAdjustID,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLAdjustID,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END    --IF @Diff_Value <> 0
            ------------------------------------------------------------------------------



            ------------------------------------------------------------------------------
            --> INSERT STOCK ADJUSTMENT table here
            ------------------------------------------------------------------------------
            IF LTRIM(RTRIM(@Note)) = ''
                BEGIN
                    IF @AdjustmentType = 1
                        BEGIN
                            SET @Note = 'Stock Adjust Qty by '
                        END
                    ELSE
                    IF @AdjustmentType = 3
                        BEGIN
                            SET @Note = 'Stock Adjust Costs by '
                        END
                    ELSE
                    IF @AdjustmentType = 6
                        BEGIN
                            SET @Note = 'Stock Adjust Take-On by '
                        END
                END
            ELSE
                BEGIN
                    SET @Note = RTRIM(LTRIM(@Note)) + ' by '
                END


			SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


            --> Stock Reval/Deval Adjustment for Last_Cost changes
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        		    @Prev_Job_Reserved,
        			@Prev_Sales_Order_Reserved,
        		    @Prev_Quote_Reserved,
        			@New_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@New_Job_Reserved ,
        			@New_Sales_Order_Reserved,
        			@New_Quote_Reserved,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO

--85 sp_AP_Update_Inventory_Cost_Adjustments
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Cost_Adjustments]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Cost_Adjustments
--Purpose       :Inserts Inventory Cost Adjustments
--Functionality :Handles Inventory Cost Adjustment Types 3 - Reval/Deval
--              :INSERT Stock Adjustment ONLY IF EITHER LastCost or AvgCost changed
--              :UPDATE GL ONLY IF ((NewLastCost or NewAvgCost) * OnHand) change has a VALUE 
--Date          :2011/04/17
--Authors       :TB
--Mods          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Avg_Cost money,
    	@New_Std_Cost money,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Avg_Cost money,
        	@OnHand decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount1 int,
            @GLControlAccount2 int,
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 3            --Reval/Deval
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    -- Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
           @Prev_Avg_Cost = ISNULL(Average_Cost, 0),
		   @OnHand = ISNULL(On_Hand, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Avg_Cost,
        Standard_Cost = @New_Std_Cost,
        [User_ID] = @UserID
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> ONLY If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Avg_Cost <> @New_Avg_Cost
		BEGIN
            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            SET @Diff_Value = 0
            SET @Narration = 'Cost Adjusment by '

            IF @ValuationMethod = 0        -- Average Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Avg_Cost - @Prev_Avg_Cost)), 2)
                END
            ELSE
            IF @ValuationMethod = 1        -- Last Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> INSERT GL Entries here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    --> Create NORMAL JOURNAL header
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END

                    --> Update INVENTORY CONTROL
                    SELECT @GLControlAccount1 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 601


                    --> Create JOURNAL DETAIL for Inventory Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount1,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Inventory Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount1,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID


                    --> Update NEW Inventory Adjustments CONTROL
    				SELECT @GLControlAccount2 = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 107


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for Cost Of Sales Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount2,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for Cost Of Sales Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLControlAccount2,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Avg_Cost,
        			@OnHand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Avg_Cost,
        			@OnHand,
        			0 ,
        			0,
        			0,
        			@Narration,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO

--86 sp_AP_Update_Inventory_Cost_Adjustments_Split_Types
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Update_Inventory_Cost_Adjustments_Split_Types
--Purpose       :Inserts SPLIT Cost Adjustments by PRODUCT TYPE and UPDATE GL
--              :    1. Inventory Control or
--              :    2. Split Inventory Control by PRODUCT TYPE if parameter is set
--Functionality :Handles Inventory Cost Adjustment Types 3 - Reval/Deval
--              :INSERT Stock Adjustment ONLY IF EITHER LastCost or AvgCost changed
--              :UPDATE GL ONLY IF ((NewLastCost or NewAvgCost) * OnHand) change has a VALUE 
--Date          :2011/04/17
--Authors       :TB
--Mods          :
--V6.0 RL	2014-05-15	:Added User ID for product audit trail
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Cost_Adjustments_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Avg_Cost money,
    	@New_Std_Cost money,
		@Month tinyint,
		@Year int,
    	@UserID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @ProdDescription varchar(50),
            @ProdCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Avg_Cost money,
        	@OnHand decimal(9,3),
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @AdjustDate datetime,
            @AdjustmentType tinyint,
            @ValuationMethod tinyint,
            @GLControlAccount int,
            @Diff_Value money,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @InsertGLTran bit,
            @SplitGRVparameter varchar(10),
            @SplitGRVTypes int,
            @TypeDescription varchar(50),
            @AdjustGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @GLAdjustID int,
            @GLInventoryID int,
            @ProductRef varchar(30)


    SET @AdjustmentsID = 0
    SET @AdjustmentType = 3            --Reval/Deval
    SET @ValuationMethod = 0           --Initialize as 'Average Cost'
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @AdjustDate = getdate()


    --> Get the Inventory Valuation setting
    EXEC sp_AW_Get_Inventory_Valuation_Method @CompanyID, @ValuationMethod OUTPUT


    --> Get the CURRENT Product values
	SELECT @ProdDescription = ISNULL(Description, ''),
           @ProdCode = LEFT(ISNULL(Product_Code, ''), 20),
           @Prev_Last_Cost = ISNULL(Last_Cost, 0),
           @Prev_Avg_Cost = ISNULL(Average_Cost, 0),
		   @OnHand = ISNULL(On_Hand, 0)		   
	FROM AP_Products
	WHERE AP_Products_ID = @ProductID


    SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


    --> Update the Product with new NEW values as per the ADJUSTMENT
	UPDATE AP_Products
    SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Avg_Cost,
        Standard_Cost = @New_Std_Cost,
		[User_ID] = @UserID        
	WHERE AP_Products_ID = @ProductID


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    --------------------------------------------------------------------
    --> If Adjustment has AN INVENTORY VALUE Increase/Decrease
    --------------------------------------------------------------------
	IF @Prev_Last_Cost <> @New_Last_Cost OR
       @Prev_Avg_Cost <> @New_Avg_Cost
		BEGIN 
            -------------------------------------------------------
            --> Get Split GRV Stock Receipts to GL INVENTORY accounts parameter
            -------------------------------------------------------
            SET @SplitGRVparameter = '0'

            SELECT @SplitGRVparameter = Control_Value
            FROM Sys_AW_Options
            WHERE Control_Type = 'CheckBox' AND
                  Control_Name = 'chkUseProductPurchasesGL' AND
                  Control_Index = 0 AND
                  AW_User_Companies_ID = @CompanyID

            -------------------------------------------------------
            --> ONLY set @SplitGRVTypes if @SplitGRVparameter = '1'
            -------------------------------------------------------
            SET @SplitGRVTypes = 0

            IF @SplitGRVparameter = '1'
                BEGIN
                    SET @SplitGRVTypes = 1
                END

            -------------------------------------------------------
            --> Get the INVENTORY CONTROL if NOT Split GRV Stock Receipts parameter
            -------------------------------------------------------
            --> Update INVENTORY CONTROL
            SELECT @GLControlAccount = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 601        --Inventory Control

            ------------------------------------------------------------
            --> Set the ADJUSTMENT VALUE
            ------------------------------------------------------------
            SET @Diff_Value = 0
            SET @Narration = 'Cost Adjusment by '

            IF @ValuationMethod = 0        -- Average Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Avg_Cost - @Prev_Avg_Cost)), 2)
                END
            ELSE
            IF @ValuationMethod = 1        -- Last Cost
                BEGIN
                    SET @Diff_Value = ROUND((@OnHand * (@New_Last_Cost - @Prev_Last_Cost)), 2)
                END

            SET @Narration = LEFT(@Narration + @User_Name + ' ' + @ProductRef, 50)

            ------------------------------------------------------------------------------
            --> NEW 2004.4.3 - Get the Product TYPE Description
            ------------------------------------------------------------------------------
            SET @TypeDescription = ''

			SELECT @TypeDescription = ISNULL(t.Description, '')
			FROM AP_Products p
                LEFT JOIN Lup_AP_Product_Types t
                    ON t.Lup_AP_Product_Types_ID = p.Lup_AP_Product_Types_ID
			WHERE p.AP_Products_ID = @ProductID


            SET @AdjustGLDescription = LEFT('ADJUSTMENT - ' + @TypeDescription, 50)
            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @TypeDescription, 50)

            ------------------------------------------------------------------------------
            --> INSERT GL ADJUSTMENT and INVENTORY account by PRODUCT TYPE here
            ------------------------------------------------------------------------------
            IF @Diff_Value <> 0
                BEGIN
                    ---------------------------------------------------------------------
                    --> Get the SPLIT GL ADJUSTMENT AccountID or CREATE a NEW GL Account
                    ---------------------------------------------------------------------
                    SET @GLAdjustID = 0

                    SELECT TOP 1 @GLAdjustID = AB_Accounts_ID
                    FROM AB_Accounts
                    WHERE AW_User_Companies_ID = @CompanyID AND
                         [Description] = @AdjustGLDescription AND
                          Sys_AB_Account_Categories_ID = 14 AND        --14 = COST OF SALES
                          Slu_AW_Active_ID = 1


                    IF @GLAdjustID = 0
                        BEGIN
             				EXEC @GLAdjustID = sp_AB_Insert_System_GL_Account
                                                    @AdjustGLDescription,
                                                    14,
                                                    @UserID,
                                                    @CompanyID
                        END

                    ---------------------------------------------------------------------
                    --> IF GRV STOCK RECEIPTS SPLIT to GL INVENTORY Accounts
                    ---------------------------------------------------------------------
                    IF @SplitGRVTypes = 1
                        BEGIN
                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID or CREATE a NEW GL Account
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0

                            SELECT TOP 1 @GLInventoryID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @InventoryGLDescription AND
                                  Sys_AB_Account_Categories_ID = 7 AND        --7 = INVENTORIES
                                  Slu_AW_Active_ID = 1


                            IF @GLInventoryID = 0
                                BEGIN
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
                            ---------------------------------------------------------------------
                        END
                    ---------------------------------------------------------------------


                    --> Create NORMAL JOURNAL header for ADJUSTMENT
                    IF @NextGLTranID = 0
                        BEGIN
             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    15,
                                    @CompanyID

            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @AdjustDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID
                        END


                    IF @SplitGRVTypes = 1
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran


                            --> Create GL TRANSACTION for SPLIT GL Inventory Account
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLInventoryID,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END
                    ELSE
                        BEGIN
                            --> Create JOURNAL DETAIL for Inventory Control 601
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @Diff_Value,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for Inventory Control 601
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    15,
                                    @GLControlAccount,
                                    @AdjustDate,
                                    @ProdCode,
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @Diff_Value,
                                    @UserID,
                                    @CompanyID
                        END


                    --> Reverse signs to balance double entry
                    SET @Diff_Value = @Diff_Value * -1


                    --> Create JOURNAL DETAIL for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLAdjustID,
                            @Diff_Value,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                    --> Create GL TRANSACTION for SPLIT GL Stock Adjustment Account
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLAdjustID,
                            @AdjustDate,
                            @ProdCode,
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Diff_Value,
                            @UserID,
                            @CompanyID

                END

            ------------------------------------------------------------------------------
            --> INSERT Stock Adjustment here
            ------------------------------------------------------------------------------
        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Avg_Cost,
        			@OnHand ,
        		    0,
        			0,
        		    0,
        			@New_Last_Cost,
                    @New_Avg_Cost,
        			@OnHand,
        			0 ,
        			0,
        			0,
        			@Narration,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO

--87 sp_AO_Update_Forecast_Product_Detail
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Update_Forecast_Product_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Update_Forecast_Product_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Description   :sp_AO_Update_Forecast_Product_Detail
--Purpose       :
--Functionality :
--Parameters    :
--Date          : 2001/08/30
--Authors       : Charl
--Version       : 1.0.0

CREATE PROCEDURE [dbo].[sp_AO_Update_Forecast_Product_Detail]
(
    @AO_Suppliers_ID int ,
	@AP_Product_ID int,
	@Service_Level Decimal(9,3),
	@Min_Order_Qty Decimal(9,3),
	@Max_Order_Qty Decimal(9,3),
	@Lead_Time smallint,
    @UserID		int 
)

AS
SET NOCOUNT ON
BEGIN

	UPDATE AP_Products 
	SET Service_Level  = @Service_Level,
		Min_Order_Qty = @Min_Order_Qty,
		Max_Order_Qty = @Max_Order_Qty,
		[User_ID] = @UserID
	WHERE AP_Products_ID = @AP_Product_ID

	UPDATE AP_Products_Suppliers
	SET Lead_Time = @Lead_Time
	WHERE AP_Products_ID = @AP_Product_ID AND
		AO_Suppliers_ID = @AO_Suppliers_ID

END 
GO

--88 sp_AF_Transaction_Detail_Insert
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Transaction_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Transaction_Detail_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Transaction_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Factory Customer Billing)
--              :    also UPDATES AP_Products: On_Hand, Last_Sale_Date
--              :         UPDATES AS_Transactions: Total_Cost
--Functionality :AS_Transactions types with Detail only: 3, 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/05/08
--Authors       :TB
--MODS          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Transaction_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitPrice money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobNo int,
        @Make int,
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
            @SmallMake varchar(6)


    SET @DocumentDetailsID = 0


    ---------------------------------------------------------------------------
    --> Set Product Cost
    ---------------------------------------------------------------------------
    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @Cost = Average_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @Cost = Last_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @Cost = Standard_Cost,
                   @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END

    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
    SET @TotalCost = ROUND(@Qty * @Cost, 2)

    UPDATE AS_Transactions
    SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
    WHERE AS_Transactions_ID = @DocumentID

    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
	IF @TranTypeID = 3    --> Invoice
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty,
                Last_Sale_Date = getdate(),
                [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
		END

	ELSE
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
		END
    ---------------------------------------------------------------------------

    SELECT @SmallMake = LEFT(ISNULL(Old_Code, ''), 6)
    FROM Lup_AP_Product_Manufacturers
    WHERE Lup_AP_Product_Manufacturers_ID = @Make


	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@Cost,
			@UnitPrice,
			@OriginalPrice,
			@Tax,
			@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

RETURN @DocumentDetailsID
GO

--89 sp_AF_Transaction_Refund_Detail_Insert
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Transaction_Refund_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Transaction_Refund_Detail_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Transaction_Refund_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (from a Factory Claim Refund)
--              :    also UPDATES AP_Products: On_Hand as OUTGOING STOCK 
--              :         UPDATES AS_Transactions: Total_Cost with FACTORY CREDIT
--Functionality :AS_Transactions types with Detail only: 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/06/29
--Authors       :TB
--MODS          :
--2004.5.5      :26/10/11 - Fixed UPDATE Header Tran Total_Cost section that set the Total_Cost =
--              :           ACTUAL FACTORY CREDITED COST. Must be current AVERAGE COST because
--              :           cost was AVERAGED when claim was RECEIVED from Factory
--V6.0	RL	2014-09-01	:Added Product audit trail info
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Transaction_Refund_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitCost money,
		@UnitPrice money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobNo int,
        @Make int,
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
            @SmallMake varchar(6)


    SET @DocumentDetailsID = 0


--     ---------------------------------------------------------------------------
--     --> Set Product Cost (The same Factory Credit that went into Inventory)
--     ---------------------------------------------------------------------------
--     SET @Cost = ROUND(@UnitCost, 2)
    SET @OriginalPrice = @Cost


    ---------------------------------------------------------------------------
    --> Set Product Cost - NEW 2004.5.5 - Copied from sp_AF_Transaction_Detail_Insert
    -->                    Because cost was AVERAGED when claim was RECEIVED
    --                     Therfore cost MUST BE TAKEN OUT at AVERAGE
    ---------------------------------------------------------------------------
    IF @CostMethod = 0        --Average
        BEGIN
            SELECT @Cost = Average_Cost
                   --@OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 1        --Last
        BEGIN
            SELECT @Cost = Last_Cost
                   --@OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END
    ELSE
    IF @CostMethod = 2        --Standard
        BEGIN
            SELECT @Cost = Standard_Cost
                   --@OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
            FROM AP_Products
            WHERE AP_Products_ID = @ProductID
        END

    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
    SET @TotalCost = ROUND(@Qty * @Cost, 2)

    UPDATE AS_Transactions
    SET Total_Cost = ISNULL(Total_Cost, 0) + @TotalCost
    WHERE AS_Transactions_ID = @DocumentID


    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI (Set as NEGATIVE)
    ---------------------------------------------------------------------------
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + -@Qty,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
		END
    ---------------------------------------------------------------------------

    SELECT @SmallMake = LEFT(ISNULL(Old_Code, ''), 6)
    FROM Lup_AP_Product_Manufacturers
    WHERE Lup_AP_Product_Manufacturers_ID = @Make


	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			-@Cost,
			-@UnitPrice,
			-@OriginalPrice,
			@Tax,
			@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

RETURN @DocumentDetailsID
GO

--90 sp_AF_Update_Deleted_Waybill_Job
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Update_Deleted_Waybill_Job]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Update_Deleted_Waybill_Job]
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Update_Deleted_Waybill_Job
--Purpose       :Update Jobs data with deleted Waybill data
--Date          :2011/05/05
--Authors       :TB
--MODS          :
--V6.0	RL	2014-09-01	:Added Product audit trail info
--V6.0	RL	2014-10-16	:Remove product quantity update.
--						 Only Waybills with no GRVs can be deleted, therefore stock has not been affected yet
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Update_Deleted_Waybill_Job]
    (
        @JobTicketID int,
        @ProductID int,
        @UserID		int
    )
AS

SET NOCOUNT ON

    DECLARE @RetCode int,
            @Prev_On_Hand Decimal(9,3),
            @New_On_Hand Decimal(9,3)


    SET @RetCode = 0

    IF @JobTicketID > 0
        BEGIN
            UPDATE AF_Job_Tickets
            SET AO_Suppliers_ID = Null,
                Waybill_Date = Null,
                AF_Waybills_ID = Null,
                Waybill_User_ID = Null
            WHERE AF_Job_Tickets_ID = @JobTicketID


--V6.0	RL	2014-10-16	:Remove product quantity update.
--						 Only Waybills with no GRVs can be deleted, therefore stock has not been affected yet
            ------------------------------------------------------------------------
            --> Updates Stock On Hand for Product
            ------------------------------------------------------------------------
         --   SELECT @Prev_On_Hand = ISNULL(On_Hand, 0)
        	--FROM AP_Products
        	--WHERE AP_Products_ID = @ProductID


         --   --> SET NEW On Hand
        	--SET @New_On_Hand = @Prev_On_Hand - 1


         --   UPDATE AP_Products
         --   SET On_Hand = @New_On_Hand,
         --   [User_ID] = @UserID
         --   WHERE AP_Products_ID = @ProductID
            ------------------------------------------------------------------------


            SET @RetCode = 1
        END

RETURN @RetCode
GO

--91 sp_AO_Select_Suppliers_From_Pended_Orders
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Suppliers_From_Pended_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Suppliers_From_Pended_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Suppliers_From_Orders
--Purpose       :Returns rs of all the suppliers in Outstanding Orders
--Functionality :
--Parameters    :
--Date          :2002/01/16
--Authors       :TB 
--MODS          :
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Suppliers_From_Pended_Orders]
    (
    	@Company_ID int
    )
AS

SET NOCOUNT ON

    SELECT AO_Suppliers_ID AS [ID],
    	   Supplier_Name
    FROM AO_Suppliers 
    WHERE AO_Suppliers_ID IN (SELECT AO_Suppliers_ID 
                              FROM AO_Orders 
                              WHERE Complete = 0 AND 
                                    AW_User_Companies_ID = @Company_ID AND
                                    Date_Ordered IS NULL) 
    AND AW_User_Companies_ID = @Company_ID
GO

--92 sp_RPT_AP_Inventory_Adjustments
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Adjustments]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Adjustments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Adjustments
--Purpose       :Retrieves filtered list of Inventory Adjustments
--Date          :2004/01/08
--Authors       :TB
--MODS          :24/02/06 - New Dynamic definition with COMMON code section
--2004.4.1      :29/09/08 - Modified Product Filter behaviour to show adjustments 
--              :           listed by ALL filters applicable to selected filter
--2004.4.2      :16/11/08 - Added @AdjustType AGAIN !!!!
--2004.4.3      :21/02/09 - Modified ORDER BY from [ORDER BY a.Date_Captured] to
--              :           [ORDER BY [Product], [Date]] to match NEW Stock Take 
--V6.0	RL	2014-09-01	:Goods Returned as an option
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Adjustments]
    (
        @CompanyID int, 
        @AdjustType tinyint,
        @SearchFilter int,
        @SearchDescription varchar(50),
        @chkDateRange tinyint,
        @StartDate datetime,
        @EndDate datetime,
        @NonStock tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @SearchDescription = RTRIM(LTRIM(@SearchDescription))


    SET @sql = ' SELECT '

    IF @SearchFilter = 3
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 4
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 5
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 1
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @SearchFilter = 2
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @SearchFilter = 6
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' a.AP_Inventory_Adjustments_ID AS [ID], '
    SET @sql = @sql + ' dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period], '
    SET @sql = @sql + ' a.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' t.[Description] AS [Type], '
    SET @sql = @sql + ' a.Note AS [Note], '
    SET @sql = @sql + ' a.Previous_On_Hand AS [Prev O/H], '
    SET @sql = @sql + ' a.New_On_Hand AS [New O/H], '
    SET @sql = @sql + ' a.Previous_Last_Cost AS [Prev Last Cost], '
    SET @sql = @sql + ' a.New_Last_Cost AS [New Last Cost], '
    SET @sql = @sql + ' a.Previous_Average_Cost AS [Prev Ave. Cost], '
    SET @sql = @sql + ' a.New_Average_Cost AS [New Ave. Cost], '
    SET @sql = @sql + ' (ISNULL(a.New_Last_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Last_Cost, 0) * ISNULL(a.Previous_On_Hand, 0)) AS [Last Cost Val], '
    SET @sql = @sql + ' (ISNULL(a.New_Average_Cost, 0) * ISNULL(a.New_On_Hand, 0)) - (ISNULL(a.Previous_Average_Cost, 0) * ISNULL(a.Previous_On_Hand, 0)) AS [Ave. Cost Val], '
    SET @sql = @sql + ' a.Date_Captured AS [Date], '
    SET @sql = @sql + ' u.UserName AS [User] '

    SET @sql = @sql + ' FROM AP_Inventory_Adjustments a '
    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + '         ON a.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AP_Adjustment_Types t '
    SET @sql = @sql + '         ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '


    IF @SearchFilter = 3
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Types o ' +
            '     ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @SearchFilter = 4
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Groups o ' +
            '     ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @SearchFilter = 5
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Departments o ' +
            '     ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @SearchFilter = 1
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @SearchFilter = 2
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '     ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @SearchFilter = 6
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


    IF @AdjustType = 1
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 1 '
        END
    ELSE
    IF @AdjustType = 2
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 2 '
        END
    ELSE
    IF @AdjustType = 3
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 3 '
        END
    ELSE
    IF @AdjustType = 4
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 4 '
        END
    ELSE
    IF @AdjustType = 5
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 5 '
        END
    ELSE
    IF @AdjustType = 6
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 6 '
        END
    ELSE
    IF @AdjustType = 7
        BEGIN
            SET @sql = @sql + ' AND a.Sys_AP_Adjustment_Types_ID = 7 '
        END

    IF @SearchFilter = 7        --> PRODUCT DESCRIPTION SEARCH
        BEGIN
            SET @sql = @sql + ' AND (p.[Description] LIKE ''%' + @SearchDescription + '%'' OR '
            SET @sql = @sql + '      p.Product_Code LIKE ''%' + @SearchDescription + '%'' ) '
        END


    IF @chkDateRange = 1   --Use Date Range
        BEGIN
            SET @sql = @sql + ' AND (a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
            SET @sql = @sql + ' AND  a.Date_Captured <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ') '
        END


    IF @NonStock = 1       --Exclude Non-Stock Items
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


--    SET @sql = @sql + ' ORDER BY a.Date_Captured '
    SET @sql = @sql + ' ORDER BY [Product], [Date] '


    EXEC (@sql)
GO

--93 sp_AS_Shape_Transaction_History_Header
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_History_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_History_Header]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_History_Header
--Purpose       :Catalog History Transaction Header Shaped
--Date          :2004/12/08
--Authors       :TB
--MODS          :08/06/05 - Moved [Comment] field forward ahead of [Amount]
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.7      :22/08/09 - Added new Select Stock Transfer TranType = 23 where required
--2004.4.8      :29/04/10 - Added [Day-End] field
--              :22/05/10 - Added CASE to [Active] field to get 'Recall XREF' Quotes and Jobs
--              :22/05/10 - Added NEW [Source No] field to show XREF Quotes and Jobs numbers
--V6.0	RL	2014-09-09	: - Added new Select Proforma TranType = 13 where required
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_History_Header]
	(
        @CustomerID int,
        @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.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Comment AS [Comment],
                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],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
                t.Total_Cost AS [Total Cost],

                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.Day_End AS [Day-End],

                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                ISNULL(ts.Transaction_Numbers, '') AS [Source No],

                CASE WHEN a.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE a.[Description]
                END 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
                LEFT JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                LEFT JOIN AS_Transaction_Sources ts
                    ON t.AS_Transactions_ID = ts.AS_Transactions_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID 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.Surname, '') + ISNULL(', ' + c.FirstNames, ''))) AS [Customer],
                tt.[Description] AS [Type],
                t.Transaction_Date AS [Date],
                t.Transaction_Number AS [Ref No],
                t.Comment AS [Comment],
                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],
                ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) AS [Balance],
                t.Total_Cost AS [Total Cost],

                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.Day_End AS [Day-End],

                ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                ISNULL(ts.Transaction_Numbers, '') AS [Source No],

                CASE WHEN a.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE a.[Description]
                END 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
                LEFT 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
                LEFT JOIN Slu_AW_Active a
                    ON t.Slu_AW_Active_ID = a.Slu_AW_Active_ID
                LEFT JOIN AS_Transaction_Sources ts
                    ON t.AS_Transactions_ID = ts.AS_Transactions_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                  t.AC_Customers_ID = @CustomerID 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 = 13 or 
                  t.Sys_AW_Transaction_Types_ID = 15 or 
                  t.Sys_AW_Transaction_Types_ID = 16 or 
                  t.Sys_AW_Transaction_Types_ID = 18 or
                  t.Sys_AW_Transaction_Types_ID = 21 or 
            	  t.Sys_AW_Transaction_Types_ID = 22 or
                  t.Sys_AW_Transaction_Types_ID = 23) AND
                  DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0
            ORDER BY Transaction_Date DESC
        END
GO

--94 Fix_Blank_Product_LU_Tables
--Update blank and NULL fields that cause errors when reporting
Update Lup_AP_Product_Locations
Set Description = 'UNKNOWN-'+Cast(Lup_AP_Product_Locations_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update Lup_AP_Product_Departments
Set Description = 'UNKNOWN-'+Cast(Lup_AP_Product_Departments_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update Lup_AP_Product_Groups
Set Description = 'UNKNOWN-'+Cast(Lup_AP_Product_Groups_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update Lup_AP_Product_Manufacturers
Set Description = 'UNKNOWN-'+Cast(Lup_AP_Product_Manufacturers_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update Lup_AP_Product_Types
Set Description = 'UNKNOWN-'+Cast(Lup_AP_Product_Types_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update AO_Suppliers
Set Supplier_Name = 'UNKNOWN-'+Cast(AO_Suppliers_ID As Varchar(10))
Where IsNull(Supplier_Name,'') = ''
Go
Update AW_Users
Set Surname = 'UNKNOWN-'+Cast(AW_Users_ID As Varchar(10))
Where IsNull(Surname,'') = ''
Go

--95 sp_AO_Select_Orders
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Orders
--Purpose       :Fetches a Supplier Order 
--Functionality :
--Parameters    :
--Date          :2002/01/15
--Authors       :TB 
--Version       :1.0
--MODS          :06/11/03 - Added JOINS to display user-friendly descriptions
--V6.0	RL	2014-09-18 :Added Fields in selects for pended orders
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Orders]
    (
    	@OrderStatus tinyint = 0,
    	@SupplierID int = 0,
    	@CompanyID int			
    )

-- @OrderStatus:    0=All, 1=Pending, 2=Outstanding, 3=Completed

AS

SET NOCOUNT ON

    BEGIN 
    --> 0 = All Orders
    	IF @OrderStatus = 0	
    		SELECT
                O.AO_Orders_ID AS [ID],
                O.Order_Number AS [Order No],
                CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                B.NodeName AS [Ordered By],
                B.NodeName AS [Branch_Codes],                    
                O.AO_Suppliers_ID AS [SupplierID],
                S.Supplier_Name AS [Supplier],
                O.Net_Amount AS [Net Amount],
                O.Tax_Total AS [Tax],
                O.Tax_Total AS [Tax Total],
                O.Order_Total AS [Total Amount],
                O.Order_Total AS [Order Total],
                (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
                 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                M.[Description] AS [Order Method],
                O.Send_To_Address AS [Deliver To],
                O.Delivery_Addr1 AS [Address],
                O.Delivery_Addr2 AS [Suburb],
                O.Delivery_Addr3 AS [City],
                O.Postal_Code AS [Post Code],
                O.Invoice_Total AS [Invoice Total],
                O.Admin_Fee  AS [Admin Fee],
                O.Trade_Discount_Total AS [Trade Disc],
                O.Trade_Discount_Total AS [Trade Discount],                
                O.Rebate_Discount_Total AS [Rebate Disc],
                O.Rebate_Discount_Total AS [Rebate Discount],
                O.Other_Discount_Total AS [Other Disc],
                O.Other_Discount_Total AS [Other Discount],
                O.Version AS [Version],
                O.Supplier_Rep AS [Supplier Rep],
                O.Supplier_Type AS [Supplier Type],
                O.Confirmation AS [Confirmed],
                O.Confirmation_Date AS [Confirm Date],
                O.Our_Ref AS [Our Ref],
                O.Supplier_Reference AS [Supplier Ref],
                O.Invoice_Type AS [Invoice Type],
                O.Date_Captured AS [Date Captured],
                O.[User_ID] AS [User ID],
                U.UserName AS [User],
                O.AW_User_Companies_ID AS [Company],
                A.[Description] AS [Active]
    		FROM AO_Orders O
                LEFT JOIN AO_Suppliers S
                    ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                LEFT JOIN AW_Remote_Access B
                    ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                LEFT JOIN Sys_AO_Delivery_Methods M
                    ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                LEFT JOIN AW_Users U
                    ON O.[User_ID] = U.AW_Users_ID
                LEFT JOIN Slu_AW_Active A
                    ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    		WHERE O.AW_User_Companies_ID = @CompanyID
    
    --> 1 = Pending Orders
    	ELSE 
    	IF @OrderStatus = 1 
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
					B.NodeName AS [Branch_Codes],                    
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],                    
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
                    O.Trade_Discount_Total AS [Trade Discount],
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NULL AND
                      O.Complete = 0 AND 
                      O.AW_User_Companies_ID = @CompanyID
    
    		ELSE 
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NULL AND
                      O.Complete = 0 AND 
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    
    		END
    --> 2 = Outstanding Orders
    	ELSE 
    	IF @OrderStatus = 2 
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NOT NULL AND
                      O.Complete = 0 AND
                      O.AW_User_Companies_ID = @CompanyID
    		ELSE
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
					O.Rebate_Discount_Total AS [Rebate Discount],                    
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Date_Ordered IS NOT NULL AND
                      O.Complete = 0 AND
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    		END
    
    --> 3 = Completed Orders
    	ELSE 
    	IF @OrderStatus = 3
    		BEGIN
    		IF @SupplierID = 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Complete = 1 AND
                      O.AW_User_Companies_ID = @CompanyID
    		ELSE
    		IF @SupplierID <> 0
        		SELECT
                    O.AO_Orders_ID AS [ID],
                    O.Order_Number AS [Order No],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Order_Date, 121)) AS [Order Date],
                    CONVERT(datetime, CONVERT(CHAR(10), O.Date_Ordered, 121)) AS [Date Ordered],
                    B.AW_Remote_Access_ID AS [Branch_Codes_ID],
                    B.NodeName AS [Ordered By],
                    O.AO_Suppliers_ID AS [SupplierID],
                    S.Supplier_Name AS [Supplier],
                    O.Net_Amount AS [Net Amount],
                    O.Tax_Total AS [Tax],
                    O.Tax_Total AS [Tax Total],
                    O.Order_Total AS [Total Amount],
                    O.Order_Total AS [Order Total],
                    (SELECT Sum(ISNULL(Order_Qty,0)) FROM AO_Order_Details 
					 WHERE AO_Orders_ID = O.AO_Orders_ID GROUP BY AO_Orders_ID ) AS [Order Qty],
                    M.[Description] AS [Order Method],
                    O.Send_To_Address AS [Deliver To],
                    O.Delivery_Addr1 AS [Address],
                    O.Delivery_Addr2 AS [Suburb],
                    O.Delivery_Addr3 AS [City],
                    O.Postal_Code AS [Post Code],
                    O.Invoice_Total AS [Invoice Total],
                    O.Admin_Fee  AS [Admin Fee],
                    O.Trade_Discount_Total AS [Trade Disc],
					O.Trade_Discount_Total AS [Trade Discount],                                    
                    O.Rebate_Discount_Total AS [Rebate Disc],
                    O.Rebate_Discount_Total AS [Rebate Discount],
                    O.Other_Discount_Total AS [Other Disc],
                    O.Other_Discount_Total AS [Other Discount],
                    O.Version AS [Version],
                    O.Supplier_Rep AS [Supplier Rep],
                    O.Supplier_Type AS [Supplier Type],
                    O.Confirmation AS [Confirmed],
                    O.Confirmation_Date AS [Confirm Date],
                    O.Our_Ref AS [Our Ref],
                    O.Supplier_Reference AS [Supplier Ref],
                    O.Invoice_Type AS [Invoice Type],
                    O.Date_Captured AS [Date Captured],
                    O.[User_ID] AS [User ID],
                    U.UserName AS [User],
                    O.AW_User_Companies_ID AS [Company],
                    A.[Description] AS [Active]
        		FROM AO_Orders O
                    LEFT JOIN AO_Suppliers S
                        ON O.AO_Suppliers_ID = S.AO_Suppliers_ID
                    LEFT JOIN AW_Remote_Access B
                        ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
                    LEFT JOIN Sys_AO_Delivery_Methods M
                        ON O.Sys_AO_Delivery_Methods_ID = M.Sys_AO_Delivery_Methods_ID
                    LEFT JOIN AW_Users U
                        ON O.[User_ID] = U.AW_Users_ID
                    LEFT JOIN Slu_AW_Active A
                        ON O.Slu_AW_Active_ID = A.Slu_AW_Active_ID
    			WHERE O.Complete = 1 AND
                      O.AO_Suppliers_ID = @SupplierID AND
                      O.AW_User_Companies_ID = @CompanyID
    		END
    	END

SET NOCOUNT OFF
GO

--96 Sys_AW_Options_POSCust_PoMessage
--Insert default Purchase Order Text in Sys_AW_Options
--txtPODocumentText
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtPODocumentText'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtPODocumentText',
		0,
		'',
		Getdate(),
		1,
		1
	)
END
GO
--chkPODocumentText
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkPODocumentText'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkPODocumentText',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--Insert Create Customer in POS option in Sys_AW_Options
--chkAllowCreateCustomer
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkAllowCreateCustomer'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkAllowCreateCustomer',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO

--97 sp_AO_Select_Purchase_Order_Data
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Purchase_Order_Data]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Purchase_Order_Data]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Purchase_Order_Data
--Purpose       :Gets data for Purchase Order Print
--Date          :2002/02/10
--Authors       :TB
--Version       :1.0.0
--MODS		    :11/11/02 - Added fields: Branch, Salesperson (Rep)
--              :06/11/03 - Replaced Lup_AW_Branch_Codes with AW_Remote_Access
--              :08/11/03 - Get Billing and Delivery addresses from AW_Remote_Access
--              :09/11/03 - Added [Credit Terms], [Supplier No], [Supplier Acct No],
--              :           [DeliveryMethod], and [OrdersURL]
--              :27/09/04 - Added selective Billing Delivery Addresses from Remote Access
--              :           or Company Catalog dependant upon value of Remote Access
--              :           Billing_Name or Delivery_Name value
--2004.3.2      :03/09/06 - Reset to fetch Billing Address from the Order
--2004.3.4      :13/12/06 - Added fetch Product_Code/Description from AP_Products
--              :           if Manufacturer Code/Description data not available
--V6.0	RL	2014-09-18	:Added Default Message To Report
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_Purchase_Order_Data]
    (
    	@OrdersID int
    )
AS

SET NOCOUNT ON

    DECLARE @SuppliersID int,
    		@CompanyID int,
            @RemoteAccessID int,
    		@Billing_Name varchar(50),
    		@Billing_Address1 varchar(40),
    		@Billing_Address2 varchar(40),
    		@Billing_Address3 varchar(40),
    		@Billing_Post_Code varchar(10),
    		@Billing_TelNo varchar(16),
    		@Billing_FaxNo varchar(16),
    		@Billing_VATNo varchar(16),
    		@Billing_RegNo varchar(16),
    		@Delivery_Name varchar(50),
    		@Delivery_Address1 varchar(40),
    		@Delivery_Address2 varchar(40),
    		@Delivery_Address3 varchar(40),
    		@Delivery_Post_Code varchar(10),
    		@Default_Message varchar(500)


	SELECT @SuppliersID = AO_Suppliers_ID,
		   @CompanyID = AW_User_Companies_ID,
           @RemoteAccessID = AW_Remote_Access_ID
	FROM AO_Orders 
	WHERE AO_Orders_ID = @OrdersID

	SET @Default_Message = ''
	SELECT @Default_Message = ISNULL(Control_Value,'')
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtPODocumentText'

    SELECT @Billing_Name = ISNULL(Billing_Name, ''),
           @Billing_Address1 = ISNULL(Billing_Address1, ''),
           @Billing_Address2 = ISNULL(Billing_Address2, ''),
           @Billing_Address3 = ISNULL(Billing_Address3, ''),
           @Billing_Post_Code = ISNULL(Billing_Post_Code, ''),
           @Billing_TelNo = ISNULL(Billing_TelNo, ''),
           @Billing_FaxNo = ISNULL(Billing_FaxNo, ''),
           @Billing_VATNo = ISNULL(Billing_VATNo, ''),
           @Billing_RegNo = ISNULL(Billing_RegNo, ''),
           @Delivery_Name = ISNULL(Delivery_Name, ''),
           @Delivery_Address1 = ISNULL(Delivery_Address1, ''),
           @Delivery_Address2 = ISNULL(Delivery_Address2, ''),
           @Delivery_Address3 = ISNULL(Delivery_Address3, ''),
           @Delivery_Post_Code = ISNULL(Delivery_Post_Code, '')
    FROM AW_Remote_Access
    WHERE AW_Remote_Access_ID = @RemoteAccessID


	SELECT @OrdersID AS [OrderID],
            S.Supplier_Name AS [Supp Name],	
    		S.Post_Box AS [Supp PostBox],
    		S.Post_Office AS [Supp PostOffice],
    		S.Post_Code AS [Supp PostCode],
    		S.Supplier_Telephone AS [Supp TelNo],
    		S.Supplier_Fax AS [Supp FaxNo],
    		S.Tax_Number AS [Supp TaxNo],
            O.Supplier_Rep AS [Rep],

--     		B.Billing_Name AS [Co Name],
--     		B.Billing_Address1 AS [Co Address1],
--     		B.Billing_Address2 AS [Co Address2],
--     		B.Billing_Address3 AS [Co Address3],
--     		B.Billing_Post_Code	AS [Co PostCode],
--     		B.Billing_TelNo AS [Co TelNo],
--     		B.Billing_FaxNo AS [Co FaxNo],
--     		B.Billing_VATNo AS [Co TaxNo],
--     		B.Billing_RegNo AS [Co RegNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Name
                 ELSE B.Billing_Name
            END AS [Co Name],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address1
                 ELSE B.Billing_Address1
            END AS [Co Address1],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address2
                 ELSE B.Billing_Address2
            END AS [Co Address2],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Address3
                 ELSE B.Billing_Address3
            END AS [Co Address3],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_Post_Code
                 ELSE B.Billing_Post_Code
            END	AS [Co PostCode],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_TelNo
                 ELSE B.Billing_TelNo
            END AS [Co TelNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_FaxNo
                 ELSE B.Billing_FaxNo
            END AS [Co FaxNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_VATNo
                 ELSE B.Billing_VATNo
            END AS [Co TaxNo],

            CASE WHEN RTRIM(LTRIM(@Billing_Name)) <> ''
                 THEN @Billing_RegNo
                 ELSE B.Billing_RegNo
            END AS [Co RegNo],


    		O.Date_Ordered AS [Date Ordered],
    		O.Order_Number AS [Order Number],
    		O.Our_Ref AS [Our Ref],
    		O.Supplier_Reference AS [Supp Ref],

--------------------------------------------------------------------
--2004.3.2  03/09/06 - Reset to fetch Billing Address from the Order
--------------------------------------------------------------------
            O.Send_To_Address AS [Del Name],
            O.Delivery_Addr1 AS [Del Addr1],
            O.Delivery_Addr2 AS [Del Addr2],
            O.Delivery_Addr3 AS [Del Addr3],
            O.Postal_Code AS [Del PostCode],

--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Name
--                  ELSE O.Send_To_Address
--             END AS [Del Name],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address1
--                  ELSE O.Delivery_Addr1
--             END AS [Del Addr1],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address2
--                  ELSE O.Delivery_Addr2
--             END AS [Del Addr2],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Address3
--                  ELSE O.Delivery_Addr3
--             END AS [Del Addr3],
-- 
--             CASE WHEN RTRIM(LTRIM(@Delivery_Name)) <> ''
--                  THEN @Delivery_Post_Code
--                  ELSE O.Postal_Code
--             END	AS [Del PostCode],
--------------------------------------------------------------------

    	    OD.AO_Order_Details_ID AS [ID],

--    		P.Manufacturer_Code [Product Code],
            CASE WHEN RTRIM(LTRIM(ISNULL(P.Manufacturer_Code, ''))) = ''
                 THEN P.Product_Code
                 ELSE P.Manufacturer_Code
            END AS [Product Code],

--    		P.Manufacturer_Description [Product Desc],
            CASE WHEN RTRIM(LTRIM(ISNULL(P.Manufacturer_Description, ''))) = ''
                 THEN P.Description
                 ELSE P.Manufacturer_Description
            END AS [Product Desc],

    		(OD.Order_Qty + OD.Back_Order_Qty) AS [QTY] ,
    		OD.Unit_Price AS [Unit Price],
    		OD.Trade_Discount_Amount AS [Trade Disc],
    		OD.Rebate_Discount_Amount AS [Rebate Disc],
    		OD.Other_Discount_Amount AS [Other Disc],	
    		(((OD.Order_Qty + OD.Back_Order_Qty) * OD.Unit_Price) - OD.Trade_Discount_Amount - OD.Rebate_Discount_Amount - OD.Other_Discount_Amount) AS SubTotal,
            OD.Net_Amount AS [Net Amount],
    		OD.Tax_Amount AS [Tax Amount],
    		OD.Total_Cost AS [Total Cost],
            T.[Description] AS [Credit Terms],
            S.Supplier_Number AS [Supplier No], 
            S.Old_Code AS [Supplier Acct No], 
            S.Sys_AO_Delivery_Methods_ID AS [DeliveryMethod],
            S.Orders_URL AS [OrdersURL],
            @Default_Message As [DefaultMessage]
	FROM AO_Orders O
        LEFT JOIN AO_Suppliers S 
			ON O.AO_Suppliers_ID = S.AO_Suppliers_ID 
		INNER JOIN AO_Order_Details OD
			ON O.AO_Orders_ID = OD.AO_Orders_ID 
		INNER JOIN AP_Products P 
			ON OD.AP_Products_ID = P.AP_Products_ID
        LEFT JOIN AW_Remote_Access B
            ON O.AW_Remote_Access_ID = B.AW_Remote_Access_ID
        LEFT JOIN Slu_AW_Credit_Terms T
            ON S.Slu_AW_Credit_Terms_ID = T.Slu_AW_Credit_Terms_ID
	WHERE O.AO_Orders_ID = @OrdersID   

SET NOCOUNT OFF
GO

--98 sp_AB_1100
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_1100]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_1100]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_1100
--Purpose       :GL BUDGET GENERATOR 1
--Parameters    :
--Date          :2002/12/09
--Authors       :TB
--MODS:         :08/04/03 - Fixed Option 2 retrieving correct fiscal period
--              :           actuals when generating the budget for the target period
--2004.2.7      :09/03/06 - Replaced Option 1 DROP AB_Budgets with DELETE @YearID
--              :09/03/06 - Added Option 4 DROP AB_Budgets table
--2004.5.5      :10/11/11 - Added @GLAccountID parameter to delete budget delete for
--              :           one selected GL Account
--              :10/11/11 - Added @UserID parameter to UPDATE the USER of cleared budgets
--              :10/11/11 - Added @Option 5 to delete budget delete for one selected Account Category
--              :10/11/11 - Added @Option 6 to delete budget delete for one selected GL Account
--              :10/11/11 - Reworked @Option 1 completely to SET budget = 0 instead of deleting it
--RL	V6.0	2014-10-14 - Checked if year end month = 12, If so do not add 1 to year end
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_1100]
    (
        @Option int,
        @Year int,
        @CompanyID int,
        @GLAccountID int,
        @GLCategoryID int,
        @UserID int
    )

AS

    DECLARE @YearID int,
            @MonthID int,
            @RetCode int,
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


    SET @RetCode = 0


    --> Get the Slu_AW_Years_ID for the Fiscal Year
    IF @Option = 0
        BEGIN
            SELECT @YearID = Slu_AW_Years_ID
            FROM Slu_AW_Years
            WHERE [Description] = @Year

            SET @RetCode = @YearID
        END

    --> Clear ALL Budgets for a Fiscal Year
    ELSE
    IF @Option = 1
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            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(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE AB_Budgets
            SET Budget_Amount = 0,
                [User_ID] = @UserID
            WHERE AW_User_Companies_ID = @CompanyID AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END

    --> Get the ID and Account Balance of ALL GL Accounts in ONE Category
    ELSE
    IF @Option = 2
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            -- NEW 06/03/03----------------------------------
            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(@StartMonthID, @StartYearID)
            ------------------------------------------------
        
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            SELECT a.AB_Accounts_ID AS [ID],
                  (
                      SELECT ISNULL(SUM(AB_Transaction_Amount), 0)
                      FROM AB_GL_Transactions
                      WHERE AW_User_Companies_ID = @CompanyID AND
                            AB_Accounts_ID = a.AB_Accounts_ID AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                            dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod AND
                            Sys_AB_Transaction_Types_ID <> 16
                  ) AS [Current]
            FROM AB_Accounts a
                LEFT JOIN Sys_AB_Account_Categories b
                    ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
            WHERE a.Sys_AB_Account_Categories_ID = @GLCategoryID
            ORDER BY [ID]

            SET @RetCode = 1
        END

    --> Get the ID and Account Balance of ALL Income Statement Accounts
    ELSE
    IF @Option = 3
        BEGIN
            SELECT @YearID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

            SET @RetCode = @YearID
        END

    --> DROP AB_Budgets table (Clear ALL Budgets)
    ELSE
    IF @Option = 4
        BEGIN
            if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
            drop table [dbo].[AB_Budgets]

            CREATE TABLE [dbo].[AB_Budgets] (
            	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
            	[AB_Accounts_ID] [int] NOT NULL ,
            	[Slu_AW_Years_ID] [int] NOT NULL ,
            	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
            	[Budget_Amount] [money] 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 
            ) ON [PRIMARY]

            ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
            	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
            	(
            		[AB_Budgets_ID]
            	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

            setuser

            EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'

            EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'

            EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'

            EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'

            EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'

            setuser

            SET @RetCode = 1
        END

    --> Clear ALL Budgets for a Account Category for a Fiscal Year
    ELSE
    IF @Option = 5
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            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(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE b
            SET b.Budget_Amount = 0,
                b.[User_ID] = @UserID
            FROM AB_Budgets b
                INNER JOIN AB_Accounts g
                    ON b.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE b.AW_User_Companies_ID = @CompanyID AND
                  g.Sys_AB_Account_Categories_ID = @GLCategoryID AND
                  dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(b.Slu_AW_Months_ID, b.Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END

    --> Clear ALL Budgets for a GL Account for a Fiscal Year
    ELSE
    IF @Option = 6
        BEGIN
            SELECT @MonthID = Year_End_Month_ID
            FROM AW_User_Companies
            WHERE AW_User_Companies_ID = @CompanyID

			IF @MonthID = 12
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year        --Ending Year
			ELSE
				SELECT @YearID = Slu_AW_Years_ID
				FROM Slu_AW_Years
				WHERE [Description] = @Year + 1        --Ending Year			

            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(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)


            UPDATE AB_Budgets
            SET Budget_Amount = 0,
                [User_ID] = @UserID
            WHERE AW_User_Companies_ID = @CompanyID AND
                  AB_Accounts_ID = @GLAccountID AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= @StartPeriod AND
                  dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= @EndPeriod

            SET @RetCode = 1
        END
RETURN @RetCode
GO

--99 sp_AB_Get_Fiscal_Span
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Get_Fiscal_Span]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Get_Fiscal_Span]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Fiscal_Span
--Purpose       :Get the START and END of a FISCAL YEAR
--              :    for the SELECTED ACCOUNTING PERIOD
--Parameters    :
--Date          :2003/03/05
--Authors       :TB
--MODS:         :
--2004.4.3      :13/03/09 - Modified @YearEndMonthID validation by INITIALIZING it to ZERO
--              :           and REMOVING its NULL validation
--RL	V6.0	2014-10-14 - If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Get_Fiscal_Span]
	(
        @CompanyID int,
        @YearEndMonthID int OUTPUT,
        @StartMonthID int OUTPUT,
        @StartYearID int OUTPUT,
        @SelectedMonthID int OUTPUT,
        @SelectedYearID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @YearEndMonthID = 0

    SELECT @YearEndMonthID = Year_End_Month_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

--	IF @YearEndMonthID IS NULL OR @YearEndMonthID = 0
    IF @YearEndMonthID = 0
        BEGIN
            SET @YearEndMonthID = 2
        END

	--RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
	IF @YearEndMonthID = 12
		SET @StartMonthID = 1								--FIRST month of the Financial Year	
	ELSE
		SET @StartMonthID = @YearEndMonthID + 1            --FIRST month of the Financial Year

    IF @SelectedMonthID <= @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID - 1
        END
    ELSE
    IF @SelectedMonthID > @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID
        END
        
SET NOCOUNT OFF
GO

--100 Create Index AP_Products_History
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AW_Period_Procedures_ID'
)
DROP INDEX AP_Products_History.IX_AW_Period_Procedures_ID
GO
CREATE INDEX IX_AW_Period_Procedures_ID
   ON AP_Products_History (AW_Period_Procedures_ID)
	WITH FILLFACTOR = 80
GO

--101 Collation_On_Transaction_Number
ALTER TABLE AS_Transactions
ALTER COLUMN Transaction_Number VARCHAR(19)
COLLATE SQL_Latin1_General_CP1_CI_AS NULL
GO
ALTER TABLE AC_Statement_Details
ALTER COLUMN Transaction_Number VARCHAR(19)
COLLATE SQL_Latin1_General_CP1_CI_AS NULL
GO
ALTER TABLE AC_Statement_Details_Temp
ALTER COLUMN Transaction_Number VARCHAR(19)
COLLATE SQL_Latin1_General_CP1_CI_AS NULL
GO

--102 Moved to the bottom
--103 sp_AS_CSales_Submission_REW
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW
--Purpose       :Get Sales Submission Data For Rewards Program
--Parameters    :
--Date          :2014-10-15
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW]
AS

SET NOCOUNT ON

	DECLARE @LastDayEnd				DateTime,
			@Temp_No_Days			Varchar(20),	
			@No_Days				Int,
			@F_Branch_Code			Varchar(5),
			@Transaction_Type		Varchar(2),
			@Transaction_Number		Varchar(20),
			@Transaction_Date		Varchar(8),
			@Transaction_Time		Varchar(5),
			@Rep_ID					Varchar(5),
			@Rep_Name				Varchar(30),
			@Product_Code			Varchar(20),
			@Product_Description	Varchar(50),
			@Quantity				Varchar(20),
			@OLD_Transaction_Number	Varchar(20)
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	--SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') FROM AW_User_Companies
     
    SET @OLD_Transaction_Number = '' 
                      	
    SET @No_Days = 14

    SELECT TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCBillingDays'
	
	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
			
	IF Exists	
	(
		SELECT 1
		From AS_Day_Ends
	)
	BEGIN 
		SELECT @LastDayEnd = MAX(Day_End) From AS_Day_Ends
		SELECT @LastDayEnd = DateAdd(d,(@No_Days*-1),@LastDayEnd)
	END
	Else
	BEGIN		
		SELECT @LastDayEnd = '1900-01-01'
	END	
	
	DECLARE Get_Data CURSOR
	FOR
	SELECT
		CASE IsNull(t.Sys_AW_Transaction_Types_ID,'0')		--Transaction Rep
		WHEN 3 THEN 'IN'
		WHEN 4 THEN 'CN'
		ELSE 'UN'
		END,
		ISNULL(t.Transaction_Number,''),					--Transaction Number
		CONVERT(Varchar(10),t.Transaction_Date,112),		--Transaction Date
		CONVERT(Varchar(5),t.Transaction_Date,108),			--Transaction Time
		CONVERT(VARCHAR(20),IsNull(t.Lup_AS_Reps_ID,'0')),	--Transaction Rep ID
		CASE IsNull(t.Lup_AS_Reps_ID,'0')					--Transaction Rep
		WHEN '0' THEN '<UNKNOWN>'
		ELSE Replace(IsNull(r.[Description],''),',','')
		END,
		ISNULL(p.Product_Code,''),							--Product Code
		ISNULL(p.[Description],''),							--Product Description
		CONVERT(Varchar(20),ISNULL(d.Quantity,0))			--Quantity
		FROM 
		AS_Transactions t
		INNER JOIN AS_Transaction_Details d
			ON t.AS_Transactions_ID = d.AS_Transactions_ID
		LEFT OUTER JOIN AP_Products p
			ON d.AP_Products_ID = p.AP_Products_ID
		LEFT OUTER JOIN Lup_AS_Reps r
			ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID		
	WHERE 
		(t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
		t.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds		
		t.Slu_AW_Active_ID = 1 AND
		t.Transaction_Date > @LastDayEnd AND		
		t.Total_Amount <> 0
	ORDER BY t.Transaction_Date 	  	
	
	OPEN Get_Data
	
	FETCH NEXT FROM Get_Data INTO 
		@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
		@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SELECT @Rep_Name = Replace(@Rep_Name,',',' ')
		SELECT @Product_Code = Replace(@Product_Code,',',' ')
		SELECT @Product_Description = Replace(@Product_Description,',',' ')				
		
		IF @OLD_Transaction_Number != @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'H' + ',' +
				@Transaction_Number + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +
				@Transaction_Type + ',' +
				@Rep_ID + ' - ' + @Rep_Name + ','
			)
		END
		
		SET @OLD_Transaction_Number = @Transaction_Number		
		
		IF @OLD_Transaction_Number = @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'D' + ',' +
				@Transaction_Number + ',' +
				@Product_Code + ',' +
				@Quantity + ',' + 
				@Transaction_Type + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +				
				@Product_Description + ','
			)
		END			
				
		FETCH NEXT FROM Get_Data INTO 
			@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
			@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity	
	END	
	CLOSE Get_Data
	Deallocate Get_Data

	SELECT [Rec] FROM @Tbl_F

SET NOCOUNT OFF
GO

--104 sp_RPT_AC_Inactive_Customers
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Inactive_Customers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Inactive_Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Inactive_Customers
--Purpose       :Fetches Inactive Customers
--Functionality :Conditional upon - No Sales since Last_Sale_Date
--Date          :2007/08/20
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Inactive_Customers]
    (
        @FromDate			datetime,
        @SortOrder			tinyint,
        @SalespersonID		int,
        @SalesAreaID		int,
        @ActiveCustomers	tinyint,
        @GroupBy			tinyint,
--        @SortBy				tinyint,
        @CompanyID			int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '

	IF @GroupBy = 1
		BEGIN
			SET @sql = @sql + ' r.[Description] AS [Group], '
		END

	IF @GroupBy = 2
		BEGIN
			SET @sql = @sql + ' s.[Description] AS [Group], '
		END

    SET @sql = @sql + ' c.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    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 + ' c.Initials AS [Initials], '
    SET @sql = @sql + ' dbo.fn_AC_Customer_Balance(c.AC_Customers_ID) AS [Balance], '
    SET @sql = @sql + ' CONVERT(CHAR(10), dbo.fn_AC_Get_Last_Sale_Date(c.AC_Customers_ID), 121) as [LastSale], '
    SET @sql = @sql + ' c.Contact_Name AS [ContactName], '
    SET @sql = @sql + ' c.Work_Email AS [Email], '
    SET @sql = @sql + ' c.Home_Email AS [ContactEmail], '
    SET @sql = @sql + ' c.Work_Tel_No AS [WorkTelNo], '
    SET @sql = @sql + ' c.Credit_Limit AS [CreditLimit], '
    SET @sql = @sql + ' c.Credit_Insurers_Limit AS [InsurerLimit], '
    SET @sql = @sql + ' c.Fax_No AS [FaxNo], '
    SET @sql = @sql + ' c.Cell_No AS [CellNo], '
    SET @sql = @sql + ' ISNULL(c.Street_Address, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Suburb, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.City, '''') + '
    SET @sql = @sql + ' ISNULL('','' + c.Street_Post_Code, '''') AS [StreetAddr], '
    SET @sql = @sql + ' a.[Description] AS [Active], '
    SET @sql = @sql + ' r.[Description] AS [Salesperson], '
    SET @sql = @sql + ' s.[Description] AS [SalesArea] '        

    SET @sql = @sql + ' FROM AC_Customers c '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a ' +
                      '         ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AS_Reps r ' +
                      '         ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AC_Sales_Areas s ' +
                      '         ON c.Lup_AC_Sales_Areas_ID = s.Lup_AC_Sales_Areas_ID '

    SET @sql = @sql + ' WHERE c.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND dbo.fn_AC_Get_Last_Sale_Date(c.AC_Customers_ID) <= ' + '''' + CONVERT(varchar(30), @FromDate)  + '''' + ' '
 --   SET @sql = @sql + '   AND dbo.fn_AC_Customer_Balance(c.AC_Customers_ID) = 0 '


	IF @SalespersonID <> 0
		BEGIN
			SET @sql = @sql + ' AND c.Lup_AS_Reps_ID = ' + CONVERT(varchar(10), @SalespersonID) + ' '
		END
		
	IF @SalesAreaID <> 0
		BEGIN
			SET @sql = @sql + ' AND c.Lup_AC_Sales_Areas_ID = ' + CONVERT(varchar(10), @SalesAreaID) + ' '
		END
		
	IF @ActiveCustomers = 1
		BEGIN
			SET @sql = @sql + ' AND c.Slu_AW_Active_ID = 1'
		END

	IF @GroupBy = 0
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY [LastSale] DESC '
				END
		END

	IF @GroupBy = 1
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY r.[Description], [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY r.[Description], [LastSale] DESC '
				END
		END

	IF @GroupBy = 2
		BEGIN
			IF @SortOrder = 0
				BEGIN
					SET @sql = @sql + ' ORDER BY s.[Description], [Customer] ASC '
				END

			ELSE    
				BEGIN
					SET @sql = @sql + ' ORDER BY s.[Description], [LastSale] DESC '
				END
		END
		
--PRINT @sql

EXEC (@sql)
GO

--105 sp_AS_Update_Zero_Cost_Transaction
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Update_Zero_Cost_Transaction]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Update_Zero_Cost_Transaction]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Update_Zero_Cost_Transaction
--Purpose       :UPDATE AS_Transaction_Details Cost
--Date          :2004/07/11
--Authors       :TB
--MODS          :
--2004.4.2      :13/11/08 - Replaced @Cost with @UnitCost to prevent confusion
--RL	V6.0	2014-10-15 - Update transaction master cost as well for Day End GL entries
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Update_Zero_Cost_Transaction]
	(
        @TranDetailID int,
        @UnitCost money
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int
	DECLARE @AS_Transactions_ID int
	DECLARE @Master_Cost int	
	
    SET @ReturnValue = 0
	SET @AS_Transactions_ID = 0
	SET @Master_Cost = 0

    IF EXISTS
        (
            SELECT AS_Transaction_Details_ID
            FROM AS_Transaction_Details
            WHERE AS_Transaction_Details_ID = @TranDetailID

        )
        BEGIN
            UPDATE AS_Transaction_Details
            SET Unit_Cost = @UnitCost
            WHERE AS_Transaction_Details_ID = @TranDetailID

			Select @AS_Transactions_ID = AS_Transactions_ID
			From AS_Transaction_Details
			Where AS_Transaction_Details_ID = @TranDetailID
			
			Select @Master_Cost = SUM(ISNULL(Unit_Cost,0) * ISNULL(Quantity,0))
			From AS_Transaction_Details
			Where AS_Transactions_ID = @AS_Transactions_ID
			
			Update AS_Transactions
			Set Total_Cost = @Master_Cost
			Where AS_Transactions_ID = @AS_Transactions_ID
			
            SET @ReturnValue = 1

        END

RETURN @ReturnValue
GO

--106 Sys_AW_Options_Customer And Supplier Email Message
--Insert default Customer E-mail message in Sys_AW_Options
--txtCustomerEmailMessage
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCustomerEmailMessage'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtCustomerEmailMessage',
		0,
		'This document has been encrypted in order to comply with the National Treasury agency’s requirements that all document types such as invoices and statements sent electronically are tamperproof.',
		Getdate(),
		1,
		1
	)
END
GO
--chkCustomerEmailMessage
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkCustomerEmailMessage'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkCustomerEmailMessage',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--Insert default Customer E-mail message in Sys_AW_Options
--txtSupplierEmailMessage
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtSupplierEmailMessage'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtSupplierEmailMessage',
		0,
		'This document has been encrypted in order to comply with the National Treasury agency’s requirements that all document types such as invoices and statements sent electronically are tamperproof.',
		Getdate(),
		1,
		1
	)
END
GO
--chkSupplierEmailMessage
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSupplierEmailMessage'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSupplierEmailMessage',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

--107 sp_AF_Select_Waybill_History_Header
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Select_Waybill_History_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Select_Waybill_History_Header]
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Select_Waybill_History_Header
--Purpose       :Selects Waybill History Header
--Date          :2011/04/27
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Select_Waybill_History_Header]
	(
        @ChkDate tinyint,
        @FromDate datetime,
        @ToDate datetime,
        @ChkCustomer tinyint,
        @CustomerID int,       
        @CompanyID int        
	)

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(100)


    SET @sql = ' SELECT Distinct '

    SET @sql = @sql + ' h.AF_Waybills_ID AS [ID], '
    SET @sql = @sql + ' s.Supplier_Name AS [Factory], '
    SET @sql = @sql + ' h.AF_Waybills_ID AS [Waybill No], '
    SET @sql = @sql + ' h.Waybill_Date AS [Waybill Date], '
    SET @sql = @sql + ' ISNULL(u.FirstName + '' '', '''') + ISNULL(u.Surname, '''') AS [User], '
    SET @sql = @sql + ' a.[Description] AS [Active], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [ActiveID] '
    SET @sql = @sql + ' FROM AF_Waybills h '
    SET @sql = @sql + '     LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON h.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AF_Job_Tickets t '
    SET @sql = @sql + '         ON h.AF_Waybills_ID = t.AF_Waybills_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON h.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Active a '
    SET @sql = @sql + '         ON h.Slu_AW_Active_ID = a.Slu_AW_Active_ID '
    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '


    IF @ChkDate = 1
        BEGIN
            SET @sql = @sql + ' AND (h.Waybill_Date BETWEEN ' +
                                     '''' + CONVERT(varchar(30), @FromDate) + '''' + ' '
            SET @sql = @sql + ' AND ' +
                                     '''' + CONVERT(varchar(30), @ToDate) + '''' + ') '
        END

    IF @ChkCustomer = 1
        BEGIN
            SET @sql = @sql + ' AND t.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
        END

    SET @sql = @sql + ' ORDER BY [Waybill Date] DESC '

--PRINT @sql

    EXEC (@sql)
GO

--108 Create AF_Delete_Audit_Tables
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AF_Job_Tickets_Deleted]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN

CREATE TABLE [AF_Job_Tickets_Deleted]
(
	[AF_Job_Tickets_ID] [int] NULL,
	[Post] [bit] NULL,
	[Job_No] [int] NULL,
	[Job_Date] [datetime] NULL,
	[AC_Customers_ID] [int] NULL,
	[Order_No] [varchar](20) NULL,
	[AP_Products_ID] [int] NULL,
	[Lup_AP_Product_Manufacturers_ID] [int] NULL,
	[Serial_No] [varchar](13) NULL,
	[Lup_AF_Instructions_ID] [smallint] NULL,
	[Job_User_ID] [int] NULL,
	[AF_Waybills_ID] [int] NULL,
	[AO_Suppliers_ID] [int] NULL,
	[Waybill_Date] [datetime] NULL,
	[Waybill_User_ID] [int] NULL,
	[AO_GRV_ID] [int] NULL,
	[GRV_Date] [datetime] NULL,
	[Invoice_No] [varchar](20) NULL,
	[Retread_Cost] [money] NULL,
	[Repair_Cost] [money] NULL,
	[Other_Cost] [money] NULL,
	[AP_Repair_Products_ID] [int] NULL,
	[AP_Other_Products_ID] [int] NULL,
	[Lup_AP_Fail_Reasons_ID] [smallint] NULL,
	[GRV_User_ID] [int] NULL,
	[AS_Transactions_ID] [int] NULL,
	[Billing_Date] [datetime] NULL,
	[Billing_No] [varchar](20) NULL,
	[Retread_Price] [money] NULL,
	[Repair_Price] [money] NULL,
	[Other_Price] [money] NULL,
	[Amount] [money] NULL,
	[Tax] [money] NULL,
	[Total] [money] NULL,
	[Comment] [varchar](20) NULL,
	[Billing_User_ID] [int] NULL,
	[AP_Inventory_Adjustments_ID] [int] NULL,
	[Adjustment_Date] [datetime] NULL,
	[AP_Stock_Products_ID] [int] NULL,
	[Casing_Credit] [money] NULL,
	[Stock_Cost] [money] NULL,
	[Adjustment_User_ID] [int] NULL,
	[Date_Captured] [datetime] NULL,
	[AW_User_Companies_ID] [int] NOT NULL,
	[Slu_AW_Active_ID] [tinyint] NULL,
	[Action_Date] [datetime] NULL,
	[Action_User_ID] [int] NULL	
)	
END
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AF_Waybills_Deleted]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
CREATE TABLE [AF_Waybills_Deleted]
(
	[AF_Waybills_ID] [int] NULL,
	[AO_Suppliers_ID] [int] NULL,
	[Waybill_Date] [datetime] NULL,
	[Date_Captured] [datetime] NULL,
	[User_ID] [int] NULL,
	[AW_User_Companies_ID] [int] NULL,
	[Slu_AW_Active_ID] [tinyint] NULL,
	[Action_Date] [datetime] NULL,
	[Action_User_ID] [int] NULL	
)	
END	
GO

--109 sp_AF_Delete_Job_Ticket
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Delete_Job_Ticket]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Delete_Job_Ticket]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AF_Delete_Job_Ticket
--Purpose       :Deletes a selected Job Ticket ONLY IF IT HAS NOT BEEN GRV'D
--Date          :2011/06/10
--Authors       :TB
--MODS          : 
--RL	V6.0	2014-10-16 :Added Delete audit trail on Job Tickets & Waybills
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Delete_Job_Ticket]
    (
        @TicketID int,
        @UserID int
    )
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int
    Declare @AF_Waybills_ID		Int
    Declare @AF_Waybills_Count	Int

	Set @AF_Waybills_ID = 0
	Set @AF_Waybills_Count = 0
	
	Select @AF_Waybills_ID = ISNULL(AF_Waybills_ID,-1)
	From AF_Job_Tickets
	Where AF_Job_Tickets_ID = @TicketID

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AF_Job_Tickets_ID
            FROM AF_Job_Tickets
            WHERE AF_Job_Tickets_ID = @TicketID AND
                  AO_GRV_ID IS NULL
        )
        BEGIN
			Insert Into AF_Job_Tickets_Deleted
			(
				AF_Job_Tickets_ID,
				Post,
				Job_No,
				Job_Date,
				AC_Customers_ID,
				Order_No,
				AP_Products_ID,
				Lup_AP_Product_Manufacturers_ID,
				Serial_No,
				Lup_AF_Instructions_ID,
				Job_User_ID,
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Waybill_User_ID,
				AO_GRV_ID,
				GRV_Date,
				Invoice_No,
				Retread_Cost,
				Repair_Cost,
				Other_Cost,
				AP_Repair_Products_ID,
				AP_Other_Products_ID,
				Lup_AP_Fail_Reasons_ID,
				GRV_User_ID,
				AS_Transactions_ID,
				Billing_Date,
				Billing_No,
				Retread_Price,
				Repair_Price,
				Other_Price,
				Amount,
				Tax,
				Total,
				Comment,
				Billing_User_ID,
				AP_Inventory_Adjustments_ID,
				Adjustment_Date,
				AP_Stock_Products_ID,
				Casing_Credit,
				Stock_Cost,
				Adjustment_User_ID,
				Date_Captured,
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				Action_Date,
				Action_User_ID
			)        
			Select         
				AF_Job_Tickets_ID,
				Post,
				Job_No,
				Job_Date,
				AC_Customers_ID,
				Order_No,
				AP_Products_ID,
				Lup_AP_Product_Manufacturers_ID,
				Serial_No,
				Lup_AF_Instructions_ID,
				Job_User_ID,
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Waybill_User_ID,
				AO_GRV_ID,
				GRV_Date,
				Invoice_No,
				Retread_Cost,
				Repair_Cost,
				Other_Cost,
				AP_Repair_Products_ID,
				AP_Other_Products_ID,
				Lup_AP_Fail_Reasons_ID,
				GRV_User_ID,
				AS_Transactions_ID,
				Billing_Date,
				Billing_No,
				Retread_Price,
				Repair_Price,
				Other_Price,
				Amount,
				Tax,
				Total,
				Comment,
				Billing_User_ID,
				AP_Inventory_Adjustments_ID,
				Adjustment_Date,
				AP_Stock_Products_ID,
				Casing_Credit,
				Stock_Cost,
				Adjustment_User_ID,
				Date_Captured,
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				GETDATE(),
				@UserID
			From AF_Job_Tickets
            Where AF_Job_Tickets_ID = @TicketID
			        
            DELETE AF_Job_Tickets
            WHERE AF_Job_Tickets_ID = @TicketID

			Select @AF_Waybills_Count = COUNT(*)
			From AF_Job_Tickets
			Where ISNULL(AF_Waybills_ID,0) = @AF_Waybills_ID

			If @AF_Waybills_Count = 0
			Begin
				Exec sp_AF_Delete_Waybill @AF_Waybills_ID, @UserID
			End
			
            SET @ReturnValue = 1
        END

RETURN @ReturnValue
GO

--110 sp_AF_Delete_Waybill
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Delete_Waybill]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Delete_Waybill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AF_Delete_Waybill
--Purpose       :Deletes a selected Waybill
--Date          :2011/05/05
--Authors       :TB
--MODS          :
--RL	V6.0	2014-10-16 :Added Delete audit trail on Waybills
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AF_Delete_Waybill]
    (
        @WaybillID int,
        @UserID int
    )
AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0

    IF EXISTS
        (
            SELECT AF_Waybills_ID
            FROM AF_Waybills
            WHERE AF_Waybills_ID = @WaybillID
        )
        BEGIN
			Insert Into AF_Waybills_Deleted
			(
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Date_Captured,
				[User_ID],
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				Action_Date,
				Action_User_ID
			)
			Select 
				AF_Waybills_ID,
				AO_Suppliers_ID,
				Waybill_Date,
				Date_Captured,
				[User_ID],
				AW_User_Companies_ID,
				Slu_AW_Active_ID,
				GETDATE(),
				@UserID
			From AF_Waybills
            Where AF_Waybills_ID = @WaybillID			
			
            DELETE AF_Waybills
            WHERE AF_Waybills_ID = @WaybillID

            SET @ReturnValue = 1
        END

RETURN @ReturnValue
GO

--111 vw_RPT_AC_Customer_List
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_RPT_AC_Customer_List]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_RPT_AC_Customer_List]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :vw_RPT_AC_Customer_List
--Purpose       :Customer Catalog Listing Report
--Parameters    :
--Date          :2002/01/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :19/09/03 - Added c.AW_User_Companies_ID AS [CompanyID] for MULTI-Company
--RL	V6.0	2014-10-21 : Added Customer Type Description, Customer Group Description
--							 Old_Customer_Number (Merchant / WHouse No), Principal Firstname
--							 Principal Name, Principal Cell No and Account Type
-------------------------------------------------------------------------------

CREATE VIEW [dbo].[vw_RPT_AC_Customer_List]
AS

SELECT
    c.AC_Customers_ID AS [ID], 
	c.Customer_Number AS [Customer No], 
	c.Surname AS [Name], 
	c.Firstnames AS [First Names], 
	CASE WHEN t.[Description] = '<None>' OR t.[Description] IS NULL
         THEN ''
         ELSE t.[Description]
         END AS [Title], 
	c.Initials AS [Initials], 
	l.[Description] AS [Language], 
	c.IDReg_Number AS [ID/Reg No], 
	c.Start_Date AS [Start Date], 
	a.[Description] AS [Active], 
	s.[Description] AS [Account Status],
	c.Contact_Name AS [Contact Name], 
	r.[Description] AS [Salesperson],
	c.Post_Box AS [Post Box], 
	c.Post_Office AS [Post Office], 
	c.Post_Code AS [Post Code], 
	c.Street_Address AS [Street Address], 
	c.Suburb AS [Suburb], 
	c.City AS [City], 
	c.Street_Post_Code AS [Street Code], 
	cu.[Description] + ' (' + cu.Country_Code3 + ')' AS [Country], 
	c.Delivery_Address AS [Delivery Address], 
	c.Delivery_Suburb AS [Delivery Suburb], 
	c.Delivery_City AS [Delivery City], 
	c.Delivery_Post_Code AS [Delivery Post Code], 
	c.Web_Site_URL AS [Web Site URL], 
	c.Orders_URL AS [Order URL], 
	c.Home_Email AS [E-mail Home], 
	c.Work_Email AS [E-mail Work],
	c.Home_Tel_No AS [Home Tel No], 
	c.Work_Tel_No AS [Work Tel No], 
	c.Cell_No AS [Cell No], 
	c.Fax_No AS [Fax No], 
	dc.[Description] AS [Sales Discount], 
	c.Credit_Limit AS [Credit Limit], 
	ct.[Description] AS [Credit Terms],
	c.Credit_Insurers_Reference AS [Credit Insurers Ref],
	c.Credit_Insurers_Limit AS [Credit Insurers Limit],
	ci.[Description] AS [Charge Interest],
	sa.[Description] AS [Sales Area], 
	c.Head_Office AS [Head Office], 
	tc.[Description] AS [Tax Code], 
	c.Tax_Number AS [Tax Number],
	act.[Description] AS [Account Types],
	ctt.[Description] AS [Credit Term Types],
	c.Notes,
    c.AW_User_Companies_ID AS [CompanyID],
    ty.[Description] AS [Customer Type],
    gr.[Description] AS [Customer Group],
    c.Old_Customer_Number AS [Merch / WHouse],
    c.Principal_Firstname AS [Principal Firstname],
    c.Principal_Name AS [Principal Name],
    c.Principal_Cell_No AS [Principal Cell No],
	act.[Description] AS [Account Type],
	c.Slu_AW_Active_ID AS [Slu_AW_Active_ID],
	c.Sys_AC_Account_Status_ID AS [Sys_AC_Account_Status_ID],
	c.Lup_AC_Customer_Groups_ID AS [Lup_AC_Customer_Groups_ID],
	c.Lup_AC_Customer_Types_ID AS [Lup_AC_Customer_Types_ID],
	c.Lup_AS_Reps_ID AS [Lup_AS_Reps_ID],	
	c.Lup_AC_Sales_Areas_ID As [Lup_AC_Sales_Areas_ID]
FROM AC_Customers c
        LEFT JOIN Slu_AW_Titles t
            ON c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
        LEFT JOIN Slu_AW_Languages l
            ON c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
        LEFT JOIN Slu_AW_Active a
            ON c.Slu_AW_Active_ID = a.Slu_AW_Active_ID
        LEFT JOIN Sys_AC_Account_Status s
            ON c.Sys_AC_Account_Status_ID = s.Sys_AC_Account_Status_ID
        LEFT JOIN Lup_AS_Reps r
            ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
        LEFT JOIN Slu_AW_Countries cu
            ON c.Slu_AW_Countries_ID = cu.Slu_AW_Countries_ID
        LEFT JOIN Lup_AC_Discount_Categories dc
            ON c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
        LEFT JOIN Slu_AW_Credit_Terms ct
            ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID
        LEFT JOIN Slu_AW_YesNo ci
            ON c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
        LEFT JOIN Lup_AC_Customer_Types ty
            ON c.Lup_AC_Customer_Types_ID = ty.Lup_AC_Customer_Types_ID
        LEFT JOIN Sys_AW_Tax_Codes tc
            ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
        LEFT JOIN Lup_AC_Sales_Areas sa
            ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
        LEFT JOIN Sys_AC_Account_Types act
            ON c.Sys_AC_Account_Types_ID = act.Sys_AC_Account_Types_ID
        LEFT JOIN Sys_AC_Credit_Term_Types ctt
            ON c.Sys_AC_Credit_Term_Types_ID = ctt.Sys_AC_Credit_Term_Types_ID
        LEFT JOIN Lup_AC_Customer_Groups gr
            ON c.Lup_AC_Customer_Groups_ID = gr.Lup_AC_Customer_Groups_ID
GO

--112 LUP_AS_CBillings_Providers_Maintenance
--Change inactive provider details
DELETE FROM Lup_AS_CBilling_Providers WHERE [Description] = '3Sigma'
GO
UPDATE Lup_AS_CBilling_Providers
SET Slu_AW_Active_ID = 2      
WHERE [Description] = 'Four Fleet'
GO
--Remove Centralised sales exclusion list
UPDATE Sys_AW_Options
SET Control_Value = ''
Where Control_Name = 'txtCSalesExclusions'
GO
--Change Alacrity details to CBOS
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'CBOS',
	Server_Name = 'gatekeeper.cbos.co.za',
	Login_Name = 'ftppos',
	Login_Password = '!!pos123'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Alacrity'
GO
--Change Alacrity details to CBOS
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'CBOS',
	Server_Name = 'gatekeeper.cbos.co.za',
	Login_Name = 'ftppos',
	Login_Password = '!!pos123'
Where LTRIM(RTRIM(ISNULL(Server_Name,''))) = 'gatekeeper.alacrity.co.za'
GO
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'CBOS',
	Server_Name = 'gatekeeper.cbos.co.za',
	Login_Name = 'ftppos',
	Login_Password = '!!pos123'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'CBOS'
GO
--Add HIQ Insurance Details
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Innovation Group'
)
BEGIN
	INSERT INTO Lup_AS_CBilling_Providers
	(
		[Description],
		Server_Name,
		Login_Name,
		Login_Password,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID,
		Slu_AW_Active_ID,
		Folder
	)
	VALUES
	(
		'Innovation Group',
		'intranet.za.innovation-group.com',
		'HiQ',
		'1nnovation_H!-Q',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO
--Add Dunlop Rewards Details
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Dunlop Rewards'
)
BEGIN
	INSERT INTO Lup_AS_CBilling_Providers
	(
		[Description],
		Server_Name,
		Login_Name,
		Login_Password,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID,
		Slu_AW_Active_ID,
		Folder
	)
	VALUES
	(
		'Dunlop Rewards',
		'www.dunlopzonerewards.co.za',
		'DZRewards_Spiralsoft',
		'847e43$A3-8D@A4-4Ab&*C-b0#FB-1C99Fas79ADC62',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--113 SYS_AW_Options_INS_REW_Options
--Insert HIQ Insurance File Option
--chkSendCInsuranceData
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCInsuranceData'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSendCInsuranceData',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--Insert Dunlop Rewards File Option
--chkSendCRewardsData
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSendCRewardsData'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSendCRewardsData',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

--114 sp_AW_Options_Select
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Options_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Options_Select]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Options_Select
--Purpose       :
--Functionality :MUST return @ControlValue as a STRING
--Parameters    :
--Date          :2002/09/16
--Authors       :TB
--Version       :1.0.0
--Mods          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Options_Select]
	(
		@ControlType varchar(50),
		@ControlName varchar(50),
		@ControlIndex smallint,
        @CompanyID int,
		@ControlValue varchar(250) OUTPUT
	)

AS     

SET NOCOUNT ON

	SELECT @ControlValue = Control_Value
    FROM Sys_AW_Options
    WHERE Control_Type = @ControlType AND
          Control_Name = @ControlName AND
          Control_Index = @ControlIndex AND
          AW_User_Companies_ID = @CompanyID

SET NOCOUNT OFF
GO

--115 sp_AP_Product_Inventory_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Inventory_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Inventory_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AP_Product_Inventory_Details
--Purpose       :Returns selected fields from Products for Stock Adjestments 
--Functionality :
--Parameters    :	
--Date          :2002/04/09
--Authors       :TB
--Version       :1.0.0
--MODS          :31/05/03 - Added NEW Average_Cost field
--V6.0	RL		:2014-10-28 - Reworked Job, Quote And Sales Order Reserved
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Product_Inventory_Details]
    (
    	@ProductID int
    )
AS

SET NOCOUNT ON

    SELECT
        AP_Products_ID AS [ID],
        [Description] AS [Description],
        Last_Cost AS [Last Cost],
        Average_Cost AS [Ave Cost],
        On_Hand AS [On Hand],
        --Job_Reserved AS [Job Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(AP_Products_ID)) as [Job Reserved], 
        --Sales_Order_Reserved AS [S/O Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(AP_Products_ID)) as [S/O Reserved], 
        --Quote_Reserved AS [Quote Reserved]
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(AP_Products_ID)) as [Quote Reserved]
    FROM AP_Products
    WHERE AP_Products_ID = @ProductID

SET NOCOUNT OFF
GO

--116 sp_AP_Select_Filtered_Products
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Filtered_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Filtered_Products]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AP_Select_Filtered_Products
--Functionality :Fetches products matching search criteria in Stock Adjustments
--Functionality :NB: Used by both Purchase Orders and Stock Adjustments
--Date          :2002/04/09
--Authors       :TB
--MODS          :10/11/03 - Fixed @Criteria fieldnames in the 3 WHERE strings
--              :           fixed Bitwise Operators in @Criteria WHERE clauses
--              :10/11/03 - Rebuild @SQL string and removed redundant fields
--              :05/09/04 - Added select ACTIVE products only
--              :05/09/04 - Added JOIN to Default Supplier
--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)
--        ****  :02/09/10 - Fixed WILDCARD search string use of OR in Criteria1 section and reworked script
--        ****  :02/09/10 - REMOVED WILDCARD search
--V6.0	RL		:2014-10-28 - Reworked Job, Quote And Sales Order Reserved
----------------------------------------------------------------------------

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

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_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 + ' )'
        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 + ' )'
        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 + ' )'
--                 END
        END


    SET @SQL = ' SELECT '
    SET @SQL = @SQL + ' p.AP_Products_ID as [ID], '
    SET @SQL = @SQL + ' p.Default_Supplier_ID AS [Supplier ID], '
    SET @SQL = @SQL + ' p.Description, ' 
    SET @SQL = @SQL + ' p.Product_Code as [Code], '
    SET @SQL = @SQL + ' s.Supplier_Name as [Default Supplier], ' 
    SET @SQL = @SQL + ' p.On_Hand as [On Hand], '

    SET @SQL = @SQL + ' dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1,getdate()) as [Selling 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.GetEffectivePrice(Price1_Effective_Date, Price1_Price2, Price2_Effective_Date, Price2_Price2,getdate()) as [Selling 2], '
    SET @SQL = @SQL + ' dbo.GetGrossMargin(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1, getdate(), Last_Cost) as [GP %], '
    SET @SQL = @SQL + ' p.Min_Stock_Level AS [MSL],  '
    SET @SQL = @SQL + ' p.Min_Order_Qty AS [MIN],  '
    SET @SQL = @SQL + ' p.Max_Order_Qty AS [MAX],  '
    SET @SQL = @SQL + ' p.Service_Level AS [SL], '
    SET @SQL = @SQL + ' p.Pack_Size AS [Pack], '
    --SET @SQL = @SQL + ' p.Job_Reserved AS [Job Res], '
    --SET @SQL = @SQL + ' p.Sales_Order_Reserved AS [S/O Res], '
    --SET @SQL = @SQL + ' p.Quote_Reserved AS [Quot Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) AS [Job Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(AP_Products_ID)) as [S/O Res], '
    SET @SQL = @SQL + ' CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) AS [Quot Res], '
    
    SET @SQL = @SQL + ' uof.Description AS [Unit],  '
    SET @SQL = @SQL + ' p.Measure AS [Measure],  '
    SET @SQL = @SQL + ' p.Manufacturer_Code AS [Manuf Code],  '
    SET @SQL = @SQL + ' p.Manufacturer_Description AS [Manuf Description],  '
    SET @SQL = @SQL + ' pt.Description AS [Type],  '
    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 AS [SuperCede],  '
    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 AS [Strength],  '
    SET @SQL = @SQL + ' p.Last_Sale_Date AS [Last Sale],  '
    SET @SQL = @SQL + ' p.Serial_Number AS [Serial No],  '
    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 AO_Suppliers s '
    SET @SQL = @SQL + '     ON s.AO_Suppliers_ID = p.Default_Supplier_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Mass_Codes mc '
    SET @SQL = @SQL + '     ON p.Lup_AP_Mass_Codes_ID = mc.Lup_AP_Mass_Codes_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Locations pl '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Locations_ID = pl.Lup_AP_Product_Locations_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Departments pd '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Types pt '
    SET @SQL = @SQL + '     ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID  '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Groups pg '
    SET @SQL = @SQL + '     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 '
    SET @SQL = @SQL + '     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 '
    SET @SQL = @SQL + '     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) 
	ELSE
	IF @FilterType = 7 --> Below MSL
		SET @SQL = @SQL + ' AND p.Min_Stock_Level > 0  AND p.On_Hand <= p.Min_Stock_Level'

    
    EXEC (@SQL)

SET NOCOUNT OFF
GO

--117 IX_AO_Transactions_AO_Suppliers_ID
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AO_Transactions_AO_Suppliers_ID'
)
DROP INDEX AO_Transactions.IX_AO_Transactions_AO_Suppliers_ID
GO
CREATE INDEX IX_AO_Transactions_AO_Suppliers_ID
   ON AO_Transactions (AO_Suppliers_ID)
	WITH FILLFACTOR = 80
GO

--118 alt_AC_Assets_AS_Transactions_ID
--Add AS_Transactions_ID to AC_Assets
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='AC_Assets' AND
        C.Name='AS_Transactions_ID'
) 
ALTER TABLE AC_Assets ADD AS_Transactions_ID Int NULL
GO    
       
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Assets].[AS_Transactions_ID]'
-------------------------------------------------------
GO 
UPDATE AC_Assets
SET AS_Transactions_ID = 0
WHERE AS_Transactions_ID IS NULL	
GO

--119 sp_AS_Select_Customer_Asset_Hist
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Customer_Asset_Hist]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Customer_Asset_Hist]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Customer_Asset_Hist
--Purpose       :Get Distinct Customer Asset Details
--Parameters    :
--Date          :2014-10-29
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Customer_Asset_Hist]
(
	@AC_Customers_ID	Int
)
AS

SET NOCOUNT ON

	SELECT DISTINCT               
                Make,
                Model,
                Model_Year,                
                t.[Description] AS [Asset_Type],
                Reg_No,
                Engine_No,
                Chassis_No,
                VIN_No,
                --Mileage,
                --Mileage_Date,
                Tyre_Size,
                --Tyre_Qty,
                a.Lup_AC_Asset_Types_ID
	FROM AC_Assets a
		LEFT JOIN Lup_AC_Asset_Types t
			ON a.Lup_AC_Asset_Types_ID = t.Lup_AC_Asset_Types_ID               
	WHERE AC_Customers_ID = @AC_Customers_ID


SET NOCOUNT OFF
GO

--120 sp_AC_Customer_Assets_Insert_Update
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Assets_Insert_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Assets_Insert_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Assets_Insert_Update
--Purpose       : 
--Functionality : 
--Parameters    : 
--Date          :2002/03/12
--Authors       :TB
--Version       :1.0.0
--MODS          :21/07/03 - Added Addition fields:
--              :           Model_Year, Engine_No, Chassis_No, VIN_No, Mileage_Date
--              :06/03/04 - Added Tyre_Size, Tyre_Qty
--V6.0	RL	2014-10-29	:Added AS_Transactions_ID
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Customer_Assets_Insert_Update]
    (
    	@AssetID int,
    	@CustomerID int,
    	@AssetTypeID smallint,
    	@Make varchar(30),
    	@Model varchar(30),
        @ModelYear varchar(10),
    	@RegNo varchar(10),
        @Engine varchar(24),
        @Chassis varchar(24),
        @VIN varchar(24),
    	@Mileage varchar(10),
        @MileageDate varchar(10),
        @TyreSize varchar(20),
        @TyreQty varchar(10),
        @AS_Transactions_ID int,
    	@CompanyID int,
    	@UserID int
    )

AS

SET NOCOUNT ON

    IF @AssetID > 0
		BEGIN
			UPDATE AC_Assets
            SET AC_Customers_ID = @CustomerID,
                Lup_AC_Asset_Types_ID = @AssetTypeID,
                Make = @Make,
                Model = @Model,
                Model_Year = @ModelYear,
                Reg_No = @RegNo,
                Engine_No = @Engine,
                Chassis_No = @Chassis,
                VIN_No = @VIN,
                Mileage = @Mileage,
                Mileage_Date = @MileageDate,
                Tyre_Size = @TyreSize,
                Tyre_Qty = @TyreQty,
                AW_User_Companies_ID = @CompanyID,
                [User_ID] = @UserID,
                Date_Captured = getdate(),
                AS_Transactions_ID = @AS_Transactions_ID
			WHERE AC_Assets_ID = @AssetID			
		END
	ELSE
		BEGIN	
			INSERT AC_Assets 
				(
                    AC_Customers_ID,
                    Lup_AC_Asset_Types_ID,
                    Make,
                    Model,
                    Model_Year,
                    Reg_No,
                    Engine_No,
                    Chassis_No,
                    VIN_No,
                    Mileage,
                    Mileage_Date,
                    Tyre_Size,
                    Tyre_Qty,
                    AW_User_Companies_ID,
                    [User_ID],
                    Date_Captured,
                    AS_Transactions_ID
				)
            VALUES
				(
					@CustomerID,
                    @AssetTypeID,
                    @Make,
                    @Model,
                    @ModelYear,
                    @RegNo,
                    @Engine,
                    @Chassis,
                    @VIN,
                    @Mileage,
                    @MileageDate,
                    @TyreSize,
                    @TyreQty,
                    @CompanyID,
                    @UserID,
                    GetDate(),
                    @AS_Transactions_ID
				)

			SELECT @AssetID = Scope_Identity()
			
		END

RETURN @AssetID
GO

--121 Sys_AW_Options_chkForceCustomerAssetDetails
--Insert Force Customer Asset Details
--chkForceCustomerAssetDetails
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkForceCustomerAssetDetails'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkForceCustomerAssetDetails',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

--122 sp_RPT_Customer_Delivery_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_Customer_Delivery_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_Customer_Delivery_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_Customer_Delivery_Details
--Purpose       :Get Customer Delivery Details
--Parameters    :
--Date          :2014-10-30
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

 
CREATE PROCEDURE [dbo].[sp_RPT_Customer_Delivery_Details]
	@FromDate			DateTime,
	@ToDate				DateTime,
	@AC_Customer_ID		Int,
	@Sales_Rep_ID		Int,
	@Customer_Rep_ID	Int,
	@Cashier_ID			Int,
	@Invoice			Int,
	@Refunds			Int,
	@Quotes				Int,
	@Sales_Orders		Int,
	@ProFormas			Int,
	@CompanyID			Int
AS

SET NOCOUNT ON

	DECLARE @WhichName			Tinyint
		
	DECLARE @Tbl_T Table
		(
			AS_Transaction_Details_ID	Int,
			AS_Transactions_ID		Int,
			AC_CustomersID			Int,
			Transaction_Number		Varchar(20),
			Transaction_Date		Datetime,
			Quantity				Money,
			Unit_Cost				Money,
			Tax_Amount				Money,
			Extended_Amount			Money,
			AP_Products_ID			Int,
			P_Description			Varchar(50),
			Lup_AS_Sales_Reps_ID	Int,
			Sales_Rep				Varchar(50),
			Lup_AS_Cashiers_ID		Int,
			Cashier					Varchar(50),
			Lup_AS_Customer_Reps_ID	Int,
			Customer_Rep			Varchar(50),	
			Lup_AC_Sales_Areas_ID	Int,
			Customer_Sales_Area		Varchar(50),			
			
			C_Surname				Varchar(40),
			C_Initials				Varchar(10),
			C_Firstnames			Varchar(50),
			C_Title					Varchar(50),						
			C_ID_Number				Varchar(20),
			C_PostalAddress1		Varchar(40),			
			C_PostalAddress2		Varchar(40),
			C_PostalCode			Varchar(10),
			C_HomeTelNo				Varchar(20),
			C_WorkTelNo				Varchar(20),
			C_MobileTelNo			Varchar(20),
			C_Street_Address		Varchar(40),
			C_Suburb				Varchar(30),
			C_City					Varchar(30),
			C_Street_Post_Code		Varchar(10),
			C_Delivery_Address		Varchar(40),
			C_Delivery_Suburb		Varchar(40),
			C_Delivery_City			Varchar(30),
			C_Delivery_Post_Code	Varchar(10),

			T_Surname				Varchar(50),
			T_Inv_Address1			Varchar(40),
			T_Inv_Address2			Varchar(40),
			T_Inv_City				Varchar(40),
			T_Inv_Code				Varchar(10),
			T_Delivery_Address		Varchar(40),
			T_Delivery_Suburb		Varchar(40),
			T_Delivery_City			Varchar(30),
			T_PostalCode			Varchar(10)
		)		
                      	
	SELECT TOP 1 @WhichName = ISNULL(Control_Index, '0')
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
	Control_Name = 'optPOSPrintAddress' AND
	Control_Value = 'True'			  

	--Insert Sales Records
	INSERT INTO @Tbl_T
	(
		AS_Transaction_Details_ID, AS_Transactions_ID, AC_CustomersID, Transaction_Number, Transaction_Date, 		
		Quantity, Unit_Cost, Tax_Amount, Extended_Amount, 
		
		AP_Products_ID, P_Description,
		Lup_AS_Sales_Reps_ID, Sales_Rep, 
		Lup_AS_Cashiers_ID, Cashier, 
		Lup_AS_Customer_Reps_ID, Customer_Rep, 
		Lup_AC_Sales_Areas_ID, Customer_Sales_Area,	

		C_Surname, C_Initials, C_Firstnames,
		C_Title, C_ID_Number, C_PostalAddress1, 
		C_PostalAddress2, C_PostalCode, 
		C_HomeTelNo, C_WorkTelNo, C_MobileTelNo,	
		C_Street_Address, C_Suburb,	C_City,	C_Street_Post_Code,
		
		C_Delivery_Address,	C_Delivery_Suburb, C_Delivery_City,	C_Delivery_Post_Code,
		T_Surname, T_Inv_Address1, T_Inv_Address2,
		T_Inv_City, T_Inv_Code,
		T_Delivery_Address, T_Delivery_Suburb, 
		T_Delivery_City, T_PostalCode
	)
	SELECT
		DISTINCT td.AS_Transaction_Details_ID, tt.AS_Transactions_ID, tt.AC_Customers_ID, tt.Transaction_Number, tt.Transaction_Date,		
		ISNULL(td.Quantity,0), ISNULL(td.Unit_Cost,0), ISNULL(td.Tax_Amount,0), ISNULL(td.Extended_Amount,0),	
		td.AP_Products_ID, LTRIM(RTRIM(ISNULL(p.[Description],''))),
		tt.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(sr.[Description],''))),
		tt.Lup_AS_Cashiers_ID, LTRIM(RTRIM(ISNULL(u.FirstName,''))) + ' ' + LTRIM(RTRIM(ISNULL(u.Surname,''))), 
		c.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(cr.[Description],''))),
		c.Lup_AC_Sales_Areas_ID, LTRIM(RTRIM(ISNULL(sa.[Description],''))),
		
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))), LTRIM(RTRIM(ISNULL(c.Post_Box,''))),
		LTRIM(RTRIM(ISNULL(c.Post_Office,''))),	LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(c.Street_Address,''))),	LTRIM(RTRIM(ISNULL(c.Suburb,''))), LTRIM(RTRIM(ISNULL(c.City,''))), LTRIM(RTRIM(ISNULL(c.Street_Post_Code,''))),
				
		LTRIM(RTRIM(ISNULL(c.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Suburb,''))), LTRIM(RTRIM(ISNULL(c.Delivery_City,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Post_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Suburb,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_City,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Post_Code,'')))
	FROM 
		AS_Transactions tt
		INNER JOIN AS_Transaction_Details td
			ON tt.AS_Transactions_ID = td.AS_Transactions_ID
		LEFT OUTER JOIN AC_Customers c
			ON tt.AC_Customers_ID = c.AC_Customers_ID
		LEFT OUTER JOIN AS_Transactions_Address a
			ON tt.AS_Transactions_ID = a.AS_Transactions_ID
		LEFT OUTER JOIN AS_Transactions_Address_Detail d
			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID			
		LEFT OUTER JOIN Slu_AW_Titles x
			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
		LEFT OUTER JOIN AP_Products p
			ON td.AP_Products_ID = p.AP_Products_ID
		LEFT OUTER JOIN Lup_AS_Reps sr
			ON tt.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN Lup_AS_Reps cr
			ON c.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN AW_Users u
			ON tt.[User_ID] = u.AW_Users_ID
		LEFT OUTER JOIN Lup_AC_Sales_Areas sa
			ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID		
	WHERE 
		tt.Slu_AW_Active_ID = 1 AND
		tt.AW_User_Companies_ID = @CompanyID AND
--		(tt.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
--		 tt.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds			 
		 tt.Transaction_Date BETWEEN @FromDate AND @ToDate AND
		 --tt.Transaction_Date BETWEEN '2014-01-01' AND '2014-07-01' AND
		 tt.Total_Amount <> 0
		 AND tt.Sys_AW_Transaction_Types_ID IN (1,3,4,13,16)
		--AND t.AS_Transactions_ID = 49757
	






	SELECT
		CASE C_Firstnames
			WHEN '' THEN C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
													WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
													ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
												END
			ELSE C_Firstnames + ', ' + C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																	WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																	ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																END
		END AS [Customer_Delivery],
		
		CASE C_Firstnames
			WHEN '' THEN C_Surname
			ELSE C_Firstnames + ', ' + C_Surname 
		END AS [Customer],	
		CASE T_Surname
			WHEN '' THEN C_Firstnames + ' ' + C_Surname
			ELSE T_Surname
		END AS [InoicedTo],
		
		CASE @WhichName
			WHEN 0 THEN
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_PostalAddress1 + ', ' + C_PostalAddress2 + ', ' + C_PostalCode)) ,',,,',','),',,',',') 
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
			ELSE
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Street_Address + ', ' + C_Suburb + ', ' + C_City + ', ' + C_Street_Post_Code)) ,',,,',','),',,',',')
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
		END	AS [Invoice_Address],
		
		CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
			WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
			ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
		END AS [Delivery_Address],
		
		P_Description,
		CONVERT(money,(Quantity * Unit_Cost) ) AS [Quantity],
		CONVERT(money,(Extended_Amount - Tax_Amount) - (Quantity * Unit_Cost) ) AS [GP],
		CASE 
			WHEN dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) <> 0 
			THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(Extended_Amount, Tax_Amount, Quantity, Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) * 100)) 
			ELSE 0.00 
		END AS [Act GP%],
		(Extended_Amount - Tax_Amount) AS [NetSales],
		Sales_Rep AS [Sales_Rep],
		Cashier AS [Cashier],
		Customer_Rep AS [Customer_Rep],
		Customer_Sales_Area AS [Customer_Sales_Area],
		Transaction_Date				
	FROM @Tbl_T	
	ORDER BY	CASE C_Firstnames
					WHEN '' THEN C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
															WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
															ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
														END
				ELSE C_Firstnames + ', ' + C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																		WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																		ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																	END
		END

	
	
--	Transaction_Date, C_Firstnames + ', ' + C_Surname, Customer_Rep, Customer_Sales_Area
	
	
	 
SET NOCOUNT OFF
GO

--123 Sys_AW_Options_chkCostSalesEditorGL
--Insert disable uncheck of posting to GL in cost sales editor
--chkCostSalesEditorGL
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkCostSalesEditorGL'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkCostSalesEditorGL',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

--124 Sys_AW_Options_Version_Check
--Switch on prevent workstation login if application and DB versions differs
Update Sys_AW_Options 
Set Control_Value = 1
Where Control_Name = 'chkLoginVersionError'
Go

--Z4 sp_AC_Transfer_Transaction_To_Customer
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Transfer_Transaction_To_Customer]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Transfer_Transaction_To_Customer]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AC_Transfer_Transaction_To_Customer
--Purpose       :Transfers ONE Customer Transaction to another Customer
--Date          :2008/10/29
--Authors       :TB
--MODS 
--RL	V5.6	:2013-11-27 Moved invoice address details to new customer
--RL	V6.0	:2014-04-10 Fix address detail move
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Transfer_Transaction_To_Customer]
    (
        @OldCustomerID int,
        @NewCustomerID int,
        @TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @Total money,
            @Payment money,
            @Owing money,
            @TranTypeID tinyint,
            @ReturnValue int,
            @AS_Transactions_Address_ID int,
            @AS_Transactions_Address_Detail_ID int,
			@Date_Captured	datetime, 
			@User_ID	int, 
			@AW_User_Companies_ID int,
			@AW_YesNo_Delivery_Address int,
			@chkPOSPrintTradeName int

    SET @ReturnValue = 0
    SET @AS_Transactions_Address_ID = 0
	SET @AS_Transactions_Address_Detail_ID = 0
	SET @AW_YesNo_Delivery_Address = 0
	SET @chkPOSPrintTradeName = 0

    SELECT @Total = ISNULL(Total_Amount, 0),
           @Payment = ISNULL(Payment_Amount, 0),
           @TranTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    SET @Owing = @Total + @Payment

	UPDATE AS_Transactions
    SET AC_Customers_ID = @NewCustomerID
	WHERE AS_Transactions_ID = @TransactionID

     IF (@TranTypeID = 3 OR       --Invoice
          @TranTypeID = 4 OR      --Refund
          @TranTypeID = 5 OR      --Journal
          @TranTypeID = 7 OR      --Payment
          @TranTypeID = 15 OR     --Interest Journal
          @TranTypeID = 18 OR     --Settlement Discount
          @TranTypeID = 21 OR     --Back Office Payment
          @TranTypeID = 22)       --EFT Payment
        BEGIN
            UPDATE AC_Customers
            SET Account_Balance = Account_Balance - @Owing
            WHERE AC_Customers_ID = @OldCustomerID

            UPDATE AC_Customers
            SET Account_Balance = Account_Balance + @Owing
            WHERE AC_Customers_ID = @NewCustomerID
        END
	
	--V6.0 RL 2014-11-02
	UPDATE AC_Assets
	SET AC_Customers_ID	= @NewCustomerID
	WHERE AS_Transactions_ID = @TransactionID
	
	--Transfer Invoice details
	SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID,
			@AS_Transactions_Address_ID = AS_Transactions_Address_ID,
			@Date_Captured = Date_Captured,
			@User_ID = [User_ID],
			@AW_User_Companies_ID = AW_User_Companies_ID
	FROM AS_Transactions_Address
	WHERE AS_Transactions_ID = @TransactionID
	
	IF @AS_Transactions_Address_Detail_ID <> 0
	BEGIN	
		
		SELECT @chkPOSPrintTradeName = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkPOSPrintTradeName'
		AND Control_Index = 0
		
		IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions_Address
			WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
			AND AS_Transactions_Address_ID <> @AS_Transactions_Address_ID
		)
		BEGIN
			IF EXISTS
			(
				SELECT 1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID
				AND ISNULL(LTRIM(RTRIM(Delivery_Address)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_Suburb)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_City)),'') <> ''
				AND ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),'') <> ''
			)
			BEGIN
				SET @AW_YesNo_Delivery_Address = 1
			END
			
			IF EXISTS
			(
				SELECT 1
				FROM Sys_AW_Options
				WHERE Control_Name = 'optPOSPrintAddress'
				AND Control_Index = 1
				AND Control_Value = 'True'
			)
			BEGIN --Street Address
				INSERT INTO AS_Transactions_Address_Detail
				(
					AC_Customers_ID, 
					Inv_Address1, 
					Inv_Address2, 
					Inv_City, 
					Inv_Code, 
					Delivery_Address, 
					Delivery_Suburb, 
					Delivery_City, 
					Delivery_Post_Code, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Customer_Name, 
					Tax_Number, 
					AW_YesNo_Delivery_Address, 
					AW_YesNo_Invoice
				)
				SELECT 
					AC_Customers_ID, 
					ISNULL(LTRIM(RTRIM(Street_Address)),''), 
					ISNULL(LTRIM(RTRIM(Suburb)),''), 
					ISNULL(LTRIM(RTRIM(City)),''), 
					ISNULL(LTRIM(RTRIM(Street_Post_Code)),''),
					ISNULL(LTRIM(RTRIM(Delivery_Address)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Suburb)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_City)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),''), 
					@Date_Captured, 
					@User_ID,
					@AW_User_Companies_ID,
					CASE @chkPOSPrintTradeName
					WHEN 1 THEN					 
						ISNULL(Surname,'') + ' / ' + ISNULL(Firstnames,'') 
					ELSE
						ISNULL(Surname,'') 					
					END,
					ISNULL(LTRIM(RTRIM(Tax_Number)),''), 
					@AW_YesNo_Delivery_Address, 
					1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID
				
				SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
				
				UPDATE AS_Transactions_Address
				SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
				WHERE AS_Transactions_ID = @TransactionID
			END
			ELSE
			BEGIN --POSTAL Address
				INSERT INTO AS_Transactions_Address_Detail
				(
					AC_Customers_ID, 
					Inv_Address1, 
					Inv_Address2, 
					Inv_City, 
					Inv_Code, 
					Delivery_Address, 
					Delivery_Suburb, 
					Delivery_City, 
					Delivery_Post_Code, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Customer_Name, 
					Tax_Number, 
					AW_YesNo_Delivery_Address, 
					AW_YesNo_Invoice
				)
				SELECT 
					AC_Customers_ID, 
					ISNULL(LTRIM(RTRIM(Post_Box)),''), 
					ISNULL(LTRIM(RTRIM(Post_Office)),''), 
					ISNULL(LTRIM(RTRIM(City)),''), 
					ISNULL(LTRIM(RTRIM(Post_Code)),''),
					ISNULL(LTRIM(RTRIM(Delivery_Address)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Suburb)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_City)),''), 
					ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),''), 
					@Date_Captured, 
					@User_ID,
					@AW_User_Companies_ID, 
					CASE @chkPOSPrintTradeName
					WHEN 1 THEN					 
						ISNULL(Surname,'') + ' / ' + ISNULL(Firstnames,'') 
					ELSE
						ISNULL(Surname,'') 					
					END,
					ISNULL(LTRIM(RTRIM(Tax_Number)),''), 
					@AW_YesNo_Delivery_Address, 
					1
				FROM AC_Customers
				WHERE AC_Customers_ID = @NewCustomerID	
				
				SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()				
				
				UPDATE AS_Transactions_Address
				SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
				WHERE AS_Transactions_ID = @TransactionID
			END	
		END
		ELSE
		BEGIN
			UPDATE AS_Transactions_Address_Detail
			SET AC_Customers_ID = @NewCustomerID
			WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
		END
		
	END

    SET @ReturnValue = 1

    RETURN @ReturnValue

SET NOCOUNT OFF
GO

--Z16 sp_AS_POS_Products_Select
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
--RL	V5.6	:2014-04-10 - Added Sell Below Cost
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[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 @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,
		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]
                	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]                        
                	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]                        
                	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]					
					)
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)                    				
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)					
					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]					
					)                    
					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]                
        	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

--Z102 sp_AS_CSales_Submission_INS
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS
--Purpose       :Get Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
AS

SET NOCOUNT ON

	Declare @CompanyNo			Int,
			@LastDayEnd			DateTime,
			@WhichName			Tinyint,
			@Loop_Ind			Int,
			@ptrval				binary(16),
			@OffSet				Int,
			
			@AS_Transactions_ID	Int,
			@AC_CustomersID		Int,
			@Transaction_Number	Varchar(20),
			@Transaction_Date	Datetime,
			@Customer_Reference	Varchar(15), --Reg No
			@Comment			Varchar(20), --Make
			
			@Quantity			Decimal(9,3),
			@Extended_Amount	Decimal(18,3),
			@Product_Description	Varchar(50),			
			
			@F_Surname			Varchar(50),
			@F_Initials			Varchar(10),
			@F_Title			Varchar(50),
			@F_ID_Number		Varchar(20),
			@F_PostalAddress1	Varchar(40),
			@F_PostalAddress2	Varchar(40),
			@F_PostalAddress3	Varchar(40),
			@F_PostalCode		Varchar(10),
			@F_HomeTelNo		Varchar(20),
			@F_WorkTelNo		Varchar(20),
			@F_MobileTelNo		Varchar(20),
			@F_Vehicle_Desc		Varchar(50),
			@F_Vehicle_Reg_No	Varchar(50),
			@F_Branch_Code		Varchar(20),
			@F_InvoiceNo		Varchar(20),
			@F_NoOfTyres		Varchar(20),
			@F_Price			Decimal(18,2),

			@C_Surname			Varchar(40),
			@C_Initials			Varchar(10),
			@C_Firstnames		Varchar(10),
			@C_Title			Varchar(50),						
			@C_ID_Number		Varchar(20),
			@C_PostalAddress1	Varchar(40),			
			@C_PostalAddress2	Varchar(40),
			@C_PostalAddress3	Varchar(40),
			@C_PostalCode		Varchar(10),
			@C_HomeTelNo		Varchar(20),
			@C_WorkTelNo		Varchar(20),
			@C_MobileTelNo		Varchar(20),			

			@T_Surname			Varchar(50),
			@T_PostalAddress1	Varchar(40),
			@T_PostalAddress2	Varchar(40),
			@T_PostalAddress3	Varchar(40),
			@T_PostalCode		Varchar(10),			
			
			@F_TyreData_1		Varchar(8000),
			@F_TyreData_2		Varchar(8000),
			@F_TyreData_3		Varchar(8000),
			@F_TyreData_4		Varchar(8000),
			@F_TyreData_5		Varchar(8000),
			@No_Days			Int,
			@Temp_No_Days		Varchar(20)
			
	DECLARE @Tbl_T Table
		(
			AS_Transactions_ID	Int,
			AC_CustomersID		Int,
			Transaction_Number	Varchar(20),
			Transaction_Date	Datetime,
			Customer_Reference	Varchar(15), --Make
			Comment				Varchar(20), --Reg No
		
			C_Surname			Varchar(40),
			C_Initials			Varchar(10),
			C_Firstnames		Varchar(50),
			C_Title				Varchar(50),						
			C_ID_Number			Varchar(20),
			C_PostalAddress1	Varchar(40),			
			C_PostalAddress2	Varchar(40),
			C_PostalAddress3	Varchar(40),
			C_PostalCode		Varchar(10),
			C_HomeTelNo			Varchar(20),
			C_WorkTelNo			Varchar(20),
			C_MobileTelNo		Varchar(20),			

			T_Surname			Varchar(50),
			T_PostalAddress1	Varchar(40),
			T_PostalAddress2	Varchar(40),
			T_PostalAddress3	Varchar(40),
			T_PostalCode		Varchar(10)
		)
		
	DECLARE @Tbl_F Table
		(
			F_TyreData_1 Varchar(8000),
			F_TyreData_2 Varchar(8000),
			F_TyreData_3 Varchar(8000),
			F_TyreData_4 Varchar(8000),
			F_TyreData_5 Varchar(8000)
		)

	DECLARE @Tbl_F_Temp Table
		(
			[Rec] Text
		)

	SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') From AW_User_Companies
                      	
	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 @No_Days = 14

    SELECT TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
					
	If Exists	
	(
		Select 1
		From AS_Day_Ends
	)
	Begin 
		Select @LastDayEnd = MAX(Day_End) From AS_Day_Ends
		Select @LastDayEnd = DateAdd(d,(@No_Days*-1),@LastDayEnd)
	End
	Else
	Begin		
		Select @LastDayEnd = '1900-01-01'
	End	

	--Insert Sales Records
	INSERT INTO @Tbl_T
	(
		AS_Transactions_ID, AC_CustomersID, Transaction_Number, Transaction_Date, 
		Customer_Reference, Comment,		
		C_Surname, C_Initials, C_Firstnames, 
		C_Title, C_ID_Number, C_PostalAddress1, 
		C_PostalAddress2, C_PostalAddress3, C_PostalCode, 
		C_HomeTelNo, C_WorkTelNo, C_MobileTelNo,	
		T_Surname, T_PostalAddress1, T_PostalAddress2,
		T_PostalAddress3, T_PostalCode
	)
	SELECT
		t.AS_Transactions_ID, t.AC_Customers_ID, t.Transaction_Number, t.Transaction_Date,
		--LTRIM(RTRIM(ISNULL(t.Customer_Reference,''))), LTRIM(RTRIM(ISNULL(t.Comment,''))), 
		LTRIM(RTRIM(ISNULL(s.Make,''))), LTRIM(RTRIM(ISNULL(s.Reg_No,''))), 
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))), LTRIM(RTRIM(ISNULL(c.Post_Box,''))), 
		LTRIM(RTRIM(ISNULL(c.Post_Office,''))),	LTRIM(RTRIM(ISNULL(c.City,''))), LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,'')))
	FROM 
		AS_Transactions t
		LEFT OUTER JOIN AC_Customers c
			ON t.AC_Customers_ID = c.AC_Customers_ID
		LEFT OUTER JOIN AS_Transactions_Address a
			ON t.AS_Transactions_ID = a.AS_Transactions_ID
		LEFT OUTER JOIN AS_Transactions_Address_Detail d
			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID			
		LEFT OUTER JOIN Slu_AW_Titles x
			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
		LEFT OUTER JOIN AC_Assets s
			ON s.AS_Transactions_ID = t.AS_Transactions_ID	
	WHERE 
		(t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
		t.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds		
		t.Slu_AW_Active_ID = 1 AND
		t.Transaction_Date > @LastDayEnd AND
		t.Total_Amount <> 0
		--AND t.AS_Transactions_ID = 49757
	Order By t.Transaction_Date 	 

	DECLARE Get_Data CURSOR
	FOR
	SELECT 
		AS_Transactions_ID,	AC_CustomersID,	Transaction_Number,	Transaction_Date, Customer_Reference, Comment,	
		C_Surname, C_Initials, C_Firstnames, C_Title, C_ID_Number,
		C_PostalAddress1, C_PostalAddress2,	C_PostalAddress3, C_PostalCode,
		C_HomeTelNo, C_WorkTelNo, C_MobileTelNo,			
		T_Surname, T_PostalAddress1, T_PostalAddress2, T_PostalAddress3, T_PostalCode
	FROM @Tbl_T

	OPEN Get_Data
	
	FETCH NEXT FROM Get_Data INTO
		@AS_Transactions_ID, @AC_CustomersID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
		@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
		@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
		@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,			
		@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SET @F_TyreData_1 = ''
		SET @F_TyreData_2 = ''
		SET @F_TyreData_3 = ''
		SET @F_TyreData_4 = ''
		SET @F_TyreData_5 = ''
		
		SET @F_Surname = ''
		SET @F_Initials = ''
		SET @F_Title = ''
		SET @F_ID_Number = ''
		SET @F_PostalAddress1 = ''
		SET @F_PostalAddress2 = ''
		SET @F_PostalAddress3 = ''
		SET @F_PostalCode = ''
		SET @F_HomeTelNo = ''
		SET @F_WorkTelNo = ''
		SET @F_MobileTelNo = ''
		SET @F_Vehicle_Desc = ''
		SET @F_Vehicle_Reg_No = ''
		SET @F_InvoiceNo = ''
		SET @F_NoOfTyres = 0
		
		
		SELECT 
			@F_NoOfTyres = Convert(Int, SUM(ISNULL(d.Quantity,0)))
		FROM 
			AS_Transaction_Details d
		WHERE 
			AS_Transactions_ID = @AS_Transactions_ID AND
			ISNULL(d.Extended_Amount,0) <> 0 AND
			d.Slu_AW_Active_ID = 1
		
		IF @T_Surname <> ''
		BEGIN
			IF @WhichName = 1
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') + ' / ' + IsNull(@C_Firstnames,'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''				
				END
			END
			ELSE
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''				
				END
			END
			
			 IF (@T_PostalAddress1 <> '' OR @T_PostalAddress2 <> '' OR @T_PostalAddress3 <> '' OR @T_PostalCode <> '')
			 BEGIN
				SET @F_PostalAddress1 = @T_PostalAddress1
				SET @F_PostalAddress2 = @T_PostalAddress2
				SET @F_PostalAddress3 = @T_PostalAddress3
				SET @F_PostalCode = @T_PostalCode						 
			 END
			 ELSE
			 BEGIN
				SET @F_PostalAddress1 = @C_PostalAddress1
				SET @F_PostalAddress2 = @C_PostalAddress2
				SET @F_PostalAddress3 = @C_PostalAddress3
				SET @F_PostalCode = @C_PostalCode						 
			 END
		END
		ELSE
		BEGIN
			SET @F_Surname = @C_Surname
			SET @F_Initials = @C_Initials
			SET @F_Title = @C_Title
			SET @F_PostalAddress1 = @C_PostalAddress1
			SET @F_PostalAddress2 = @C_PostalAddress2
			SET @F_PostalAddress3 = @C_PostalAddress3
			SET @F_PostalCode = @C_PostalCode			
		END
		
		SET @F_ID_Number = @C_ID_Number
		SET @F_HomeTelNo = @C_HomeTelNo
		SET @F_WorkTelNo = @C_WorkTelNo
		SET @F_MobileTelNo = @C_MobileTelNo
		SET @F_Vehicle_Desc = @Customer_Reference --Make
		SET @F_Vehicle_Reg_No = @Comment --Reg No
		SET @F_InvoiceNo = @Transaction_Number
				
		SELECT @F_TyreData_1 =	'1' + ',' +
								REPLACE(@F_Surname,',','~') + ',' +
								REPLACE(@F_Initials,',','~') + ',' +
								REPLACE(@F_Title,',','~') + ',' +
								REPLACE(@F_ID_Number,',','~') + ',' +
								REPLACE(@F_PostalAddress1,',','~') + ',' +
								REPLACE(@F_PostalAddress2,',','~') + ',' +
								REPLACE(@F_PostalAddress3,',','~') + ',' +
								REPLACE(@F_PostalCode,',','~') + ',' +
								REPLACE(@F_HomeTelNo,',','~') + ',' +
								REPLACE(@F_WorkTelNo,',','~') + ',' +
								REPLACE(@F_MobileTelNo,',','~') + ',' +
								REPLACE(@F_Vehicle_Desc,',','~') + ',' +
								REPLACE(@F_Vehicle_Reg_No,',','~') + ',' +								
								REPLACE(@F_Branch_Code,',','~') + ',' +
								REPLACE(@F_InvoiceNo,',','~') + ',' +
								REPLACE(@F_NoOfTyres,',','~') + ','

		INSERT INTO @Tbl_F_Temp(Rec) Values(@F_TyreData_1)
	
		DECLARE Get_Detail CURSOR
		FOR
		SELECT 
			ISNULL(d.Quantity,0), ISNULL(d.Extended_Amount,0), LTRIM(RTRIM(ISNULL(p.Description,'')))
		FROM 
			AS_Transaction_Details d
			LEFT OUTER JOIN AP_Products p
				ON d.AP_Products_ID = p.AP_Products_ID
		WHERE 
			ISNULL(d.Extended_Amount,0) <> 0 AND
			d.Slu_AW_Active_ID = 1 AND
			d.AS_Transactions_ID = @AS_Transactions_ID
				
		OPEN Get_Detail
		
		FETCH NEXT FROM Get_Detail INTO 		
			@Quantity, @Extended_Amount, @Product_Description
			
		WHILE @@FETCH_STATUS = 0
		BEGIN
							
			SET @F_Price = 0
			SET @F_Price = Convert(Decimal(18,2), (@Extended_Amount / ABS(@Quantity)))
			
			SET @Loop_Ind = 1
			
			IF @Quantity < 0
				SET @Quantity = @Quantity * -1
			
			WHILE @Loop_Ind <= @Quantity
			BEGIN
				--SET @F_TyreData = ''
				--SET @F_TyreData =	'' + ',' +
				--					Convert(Varchar(10),@Transaction_Date,111) + ',' +
				--					Convert(Varchar(20),@F_Price) + ',' +
				--					REPLACE(@Product_Description,',','~') + ',' +
				--					'' + ','
			
				--SELECT @ptrval = TEXTPTR(Rec) FROM @Tbl_F_Temp WHERE 1 = 1
				--SELECT @OffSet = DataLength(Rec) From @Tbl_F_Temp
				----UPDATE @Tbl_F_Temp
				----SET Rec.Write(@F_TyreData,DataLength(Rec),0) -- = Rec + Convert(Text,@F_TyreData)
				--UPDATETEXT @Tbl_F_Temp.Rec @ptrval @OffSet NULL 'B'
				
				
				IF Len(@F_TyreData_1) < 7900
				BEGIN
					SET @F_TyreData_1 =	@F_TyreData_1 + 
										Convert(Varchar(10),@Transaction_Date,111) + ',' +
										Convert(Varchar(20),@F_Price) + ',' +
										REPLACE(@Product_Description,',','~') + ',' +
										'' + ','
				END
				ELSE						
				IF (Len(@F_TyreData_1) >= 7900 AND Len(@F_TyreData_2) < 7900)
				BEGIN
					SET @F_TyreData_2 =	@F_TyreData_2 + 
										Convert(Varchar(10),@Transaction_Date,111) + ',' +
										Convert(Varchar(20),@F_Price) + ',' +
										REPLACE(@Product_Description,',','~') + ',' +
										'' + ','
				END	
				ELSE					
				IF (Len(@F_TyreData_1) >= 7900 AND Len(@F_TyreData_2) >= 7900 AND Len(@F_TyreData_3) < 7900)
				BEGIN
					SET @F_TyreData_3 =	@F_TyreData_3 + 
										Convert(Varchar(10),@Transaction_Date,111) + ',' +
										Convert(Varchar(20),@F_Price) + ',' +
										REPLACE(@Product_Description,',','~') + ',' +
										'' + ','
				END	
				ELSE					
				IF (Len(@F_TyreData_1) >= 7900 AND Len(@F_TyreData_2) >= 7900 AND Len(@F_TyreData_3) >= 7900 AND Len(@F_TyreData_4) < 7900)
				BEGIN
					SET @F_TyreData_4 =	@F_TyreData_4 + 
										Convert(Varchar(10),@Transaction_Date,111) + ',' +
										Convert(Varchar(20),@F_Price) + ',' +
										REPLACE(@Product_Description,',','~') + ',' +
										'' + ','
				END
				ELSE
				IF (Len(@F_TyreData_1) >= 7900 AND Len(@F_TyreData_2) >= 7900 AND Len(@F_TyreData_3) >= 7900 AND Len(@F_TyreData_4) >= 7900 AND Len(@F_TyreData_5) < 7900)
				BEGIN
					SET @F_TyreData_5 =	@F_TyreData_5 + 
										Convert(Varchar(10),@Transaction_Date,111) + ',' +
										Convert(Varchar(20),@F_Price) + ',' +
										REPLACE(@Product_Description,',','~') + ',' +
										'' + ','
				END									
				
				SET @Loop_Ind = @Loop_Ind + 1
			END
		
			FETCH NEXT FROM Get_Detail INTO 		
				@Quantity, @Extended_Amount, @Product_Description		
		END
		CLOSE Get_Detail
		Deallocate Get_Detail
	
		--INSERT INTO @Tbl_F (Rec) --Values(@F_TyreData_1+@F_TyreData_2+@F_TyreData_3+@F_TyreData_4+@F_TyreData_5)
		--SELECT Rec FROM @Tbl_F_Temp
	
		INSERT INTO @Tbl_F (F_TyreData_1, F_TyreData_2, F_TyreData_3, F_TyreData_4, F_TyreData_5)
		VALUES(@F_TyreData_1, @F_TyreData_2, @F_TyreData_3, @F_TyreData_4, @F_TyreData_5)
	
		FETCH NEXT FROM Get_Data INTO
			@AS_Transactions_ID, @AC_CustomersID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
			@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
			@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
			@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,			
			@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode
	END
	CLOSE Get_Data
	DEALLOCATE Get_Data

	SELECT ISNULL(F_TyreData_1,'') AS [F1] , ISNULL(F_TyreData_2,'') AS [F2],
			ISNULL(F_TyreData_3,'') AS [F3], ISNULL(F_TyreData_4,'') AS [F4], ISNULL(F_TyreData_5,'') AS [F5] FROM @Tbl_F

	--SELECT Convert( Text, (ISNULL(F_TyreData_1,'') + ISNULL(F_TyreData_2,'') + 
			--ISNULL(F_TyreData_3,'') + ISNULL(F_TyreData_4,'') + ISNULL(F_TyreData_5,'')) ) As [Rec] FROM @Tbl_F

--	SELECT ISNULL(F_TyreData_1,'') FROM @Tbl_F

SET NOCOUNT OFF
GO


--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------
IF NOT EXISTS
    (
        SELECT AA_Release_ID
        FROM AA_Release
        WHERE Release = '2015.6.0'
    )
    BEGIN
        INSERT AA_Release
            (
                Release,
                Updated_by			  
            )
        VALUES
            (
                '2015.6.0',
                'Download'
            )
    END
ELSE
    BEGIN
        UPDATE AA_Release
        SET Updated_by = 'Download',
            Date_Updated = getdate()
        WHERE Release = '2015.6.0'
    END   
    
GO    





