------------------------------------------------------------------------------
-- ADVANTAGE 2017.6.3.1000
-- Sales Orders, Back Orders and minor fixes
-- 2017-12-19
------------------------------------------------------------------------------

--Prevent Logon From Incorrect App Version
UPDATE Sys_AW_Options
SET Control_Value = 1
WHERE Control_Name = 'chkLoginVersionError'
GO
--Consignment Stock GRV Linking
--Linked CRV ID
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='AO_GRV' AND
        C.Name='AO_GRV_ID_Consignment'
)
ALTER TABLE AO_GRV ADD AO_GRV_ID_Consignment varchar(20) NULL
GO
	
UPDATE AO_GRV
SET AO_GRV_ID_Consignment = ''
WHERE ISNULL(AO_GRV_ID_Consignment,'') = ''
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV].[AO_GRV_ID_Consignment]'
-------------------------------------------------------
GO

--Linked CRV Detail ID
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='AO_GRV_Details' AND
        C.Name='AO_GRV_Details_ID_Consignment'
)
ALTER TABLE AO_GRV_Details ADD AO_GRV_Details_ID_Consignment varchar(20) NULL
GO
	
UPDATE AO_GRV_Details
SET AO_GRV_Details_ID_Consignment = ''
WHERE ISNULL(AO_GRV_Details_ID_Consignment,'') = ''
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV_Details].[AO_GRV_Details_ID_Consignment]'
-------------------------------------------------------
GO

--Track Returned CRV
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='AO_GRV_Details' AND
        C.Name='Qty_Returned'
)
ALTER TABLE AO_GRV_Details ADD Qty_Returned decimal(12,3)
GO
	
UPDATE AO_GRV_Details
SET Qty_Returned = 0
WHERE ISNULL(Qty_Returned,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Returned]'
-------------------------------------------------------
GO

--Track Sold CRV
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='AO_GRV_Details' AND
        C.Name='Qty_Sold'
)
ALTER TABLE AO_GRV_Details ADD Qty_Sold decimal(12,3)
GO
	
UPDATE AO_GRV_Details
SET Qty_Sold = 0
WHERE ISNULL(Qty_Sold,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Sold]'
-------------------------------------------------------
GO


--Track Left CRV
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='AO_GRV_Details' AND
        C.Name='Qty_Left'
)
ALTER TABLE AO_GRV_Details ADD Qty_Left decimal(12,3)
GO
	
UPDATE AO_GRV_Details
SET Qty_Left = 0
WHERE ISNULL(Qty_Left,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Left]'
-------------------------------------------------------
GO

IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Returned]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Returned]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Returned
--Purpose       :Returns consignment quantity returned for a specific AS_Transaction_Detail_ID
--Parameters    :
--Date          :2015/05/21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Returned]
	(
        @AS_Transaction_Details_ID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ABS(ISNULL(SUM(Quantity), 0))
            FROM AS_Transaction_Details_Consignment
            WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID AND
				  Sys_AW_Transaction_Types_ID = 35

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

----------------------------------------------------------------------------
--Description   :sp_AP_Bins_New_Batch_No
--Functionality :Create new batch number for product bin allocations
--Parameters    :
--Date          :2015/11/19
--Authors       :RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Bins_New_Batch_No]
    (
    	@CompanyID int,
    	@Batch_No int output
    )

AS

SET NOCOUNT ON

BEGIN

	SET @Batch_No = 0
	
	SELECT @Batch_No = ISNULL(MAX(Batch_No),0)
	FROM AP_Products_Bins_History
	
	SET @Batch_No = @Batch_No + 1
	
	RETURN @Batch_No
END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Bin_Allocation]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Bin_Allocation]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation
--Purpose       :Allocates products to bins
--Functionality :
--Parameters    :
--Date          :2015-11-20
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Bin_Allocation]
    (
		@Batch_No				int,
    	@AP_Products_ID			int,
    	@From_Bin_ID			int,
    	@From_Bin_On_Hand		decimal(9,3),
    	@Orig_From_Bin_On_Hand	decimal(9,3),
    	@To_Bin_ID				int,
		@Movement_Source		varchar(10),
		@Transfer_Qty			decimal(9,3),
    	@User_ID				int,
    	@Company_ID				int,
    	@ReturnMsg				varchar(200)
    )
AS

SET NOCOUNT ON

    DECLARE @From_Bin_Previous_On_Hand	decimal(9,3),
			@From_AP_Products_Bins_ID	int,
			@To_Bin_Previous_On_Hand	decimal(9,3),			
			@To_AP_Products_Bins_ID		int

	SET @From_Bin_Previous_On_Hand = 0
	SET @From_AP_Products_Bins_ID = 0
	SET @To_Bin_Previous_On_Hand = 0
	SET @To_AP_Products_Bins_ID = 0
	--SET @Transfer_Qty = 0
	SET @ReturnMsg = ''

	--SELECT @Transfer_Qty = @Orig_From_Bin_On_Hand - @From_Bin_On_Hand

	SELECT	@From_Bin_Previous_On_Hand = On_Hand,
			@From_AP_Products_Bins_ID = AP_Products_Bins_ID
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @AP_Products_ID
	AND Lup_AP_Product_Bins_ID = @From_Bin_ID

	SELECT	@To_Bin_Previous_On_Hand = On_Hand,
			@To_AP_Products_Bins_ID = AP_Products_Bins_ID
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @AP_Products_ID
	AND Lup_AP_Product_Bins_ID = @To_Bin_ID
	
	IF (@Transfer_Qty <> 0)
	BEGIN --Bin Allocation Changed
		--IF @From_Bin_Previous_On_Hand >= @Transfer_Qty
		--BEGIN --@From_Bin_On_Hand >= @Qty
			--V6.2 Update Bin Qty
			
				EXEC sp_AP_Products_Bins_Hist_Insert 
				@AP_Products_ID,--@ProductID int,
				@From_Bin_ID,--@ProductBinID int,
				@From_Bin_Previous_On_Hand,--@From_Bin_Previous_On_Hand
				@To_Bin_ID,--@ProductBinID int,
				@To_Bin_Previous_On_Hand,--From_Bin_Previous_On_Hand
    			@Transfer_Qty,--@Qty decimal(9,3)
    			'Bin Alloc',--@Source varchar(10),
    			@Batch_No,--int,
    			@User_ID,--@UserID int,
    			@Company_ID--@CompanyID int
    			
				--SELECT @Transfer_Qty = @Transfer_Qty * -1

				--EXEC sp_AP_Products_Bins_Update_Insert 
				--@AP_Products_ID,--@ProductID int,
				--@From_Bin_ID,--@ProductBinID int,
    --			@Transfer_Qty,--@Qty decimal(9,3)
    --			'Bin Alloc',--@Source varchar(10),
    --			@Batch_No,--int,
    --			@User_ID,--@UserID int,
    --			@Company_ID--@CompanyID int

		--END --@From_Bin_On_Hand >= @Qty
		--ELSE
		--BEGIN --@From_Bin_On_Hand < @Qty
		--	SELECT @ReturnMsg = Product_Code + ' - ' + [Description] + 'From Bin Quantity Was Changed By Another User. Please Redue Allocation'
		--	FROM AP_Products
		--	WHERe AP_Products_ID = @AP_Products_ID
		--END --@From_Bin_On_Hand < @Qty
	
	END --Bin Allocation Changed
	
	RETURN @ReturnMsg	

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

-- sp_AP_Bin_Select 1, 555

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

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

AS

SET NOCOUNT ON

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

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

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

-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Default_Bin
--Purpose       :Select Users default product bin
--Parameters    :
--Date          :2015-11-20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_User_Default_Bin]
	(
        @UserID int,
		@ProductBin int OUTPUT
	)

AS

    SET @ProductBin = 0

	SELECT @ProductBin = Lup_AP_Product_Bins_ID
	FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @ProductBin IS NULL 
        BEGIN	
    		SET @ProductBin = 0 
        END
GO
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
--V6.3	RL	2017/05/03	:Inserted result set into a @table and select from there due to sum issue
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_POS_Transaction_Document_Details_Select]
    (
        @DocumentID int
    )

AS

SET NOCOUNT ON

	Declare @Tbl1 Table
	(
		[Description]			varchar(50),
		[Code]					varchar(20),
		[Qty]					decimal(9,3),		
		[Price]					money,
		[Discount]				money,
		[TotalAmount]			money,
		[Cost]					money,
		[OriginalPrice]			money,
		[Tax]					money,
		[Commission]			money,
		[PromotionProductID]	integer,
		[PromotionPrice]		money,
		[JobRefID]				integer,
		[SerialNo]				varchar(13),
		[Make]					varchar(6),
		[Customer]				varchar(20),
		[DateCaptured]			datetime,
		[UserID]				integer,
		[CompanyID]				integer,
		[DocumentDetailsID]		integer,
		[DocumentID]			integer,
		[ProductID]				integer,
		[TaxRate]				decimal(9,3),
		[TDHeader]				varchar(256),
		[TDDetail]				varchar(256),
		[ProductBinsID]			integer,
		[BackOrder]				decimal(9,3)
	)
	

	INSERT INTO @Tbl1
    SELECT 
    	p.Description as [Description],
    	p.Product_Code as [Code], 
    	--dbo.fn_AP_Get_Transaction_Qty_BO(AS_Transaction_Details_ID) AS [Qty],
    	--(d.Quantity + d.Back_Order) AS [Qty],
    	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,
        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
		d.Back_Order as [BackOrder]

    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
    
    SELECT * From @Tbl1
GO
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.2	RL	2015-11-20	:Added LUP_AP_Products_Bin
--V6.3	RL	2017-05-04  :Added Back Order Qty to Qty
--V6.3	RL	2017-09-10	:Return Back_Order
-------------------------------------------------------------------------------

CREATE PROCEDURE [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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + (d.Back_Order + d.Back_Order) ) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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 + d.Back_Order)) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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 + d.Back_Order) 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,
						        d.Lup_AP_Product_Bins_ID as [ProductBinsID],
								d.Back_Order as [BackOrder]                                
                            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
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
--V6.2 RL	2015-11-29	:Removed Job Reserved, Sales Order Reserved and Quote Reserved
--						 These values are calculation based on active transactions and not the what is in the AP_Products table
--V6.2 RL	2015-11-29	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Adjusted_Inventory_Details]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
        @ProductBinID int,
    	@New_Bin_On_Hand decimal(9,3), --From V6.2 This is the bin on hand qty
    	@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),
	    	@New_Job_Reserved decimal(9,3),
	    	@New_Sales_Order_Reserved decimal(9,3),
	    	@New_Quote_Reserved 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),
            @Prev_On_Hand_Bin decimal(9,3),
            @On_Hand_Diff_Bin decimal(9,3),
            @Prev_On_Hand_Adj decimal(9,3),
            @New_On_Hand_Adj decimal(9,3),

            @New_On_Hand decimal(9,3),            
            @On_Hand_Diff decimal(9,3),

            @AP_Products_Bins_History_ID int,
            @Batch_No int,
            @ConsignmentStock    decimal(9,3),
            @StockOffSite		decimal(9,3) 

    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()
    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    SET @Batch_No = 0

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

	--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
	--Consignment stock is not GRV'd stock
	SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID),0)
	SET @StockOffSite = ISNULL(dbo.fn_AP_Get_Products_Out_On_Consignment(@ProductID),0)
	
--Insert Into Temp_Debug Values('@ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))  	
--Insert Into Temp_Debug Values('@StockOffSite',Convert(Varchar(100),@StockOffSite))  	
--Insert Into Temp_Debug Values('@Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))  	
--Insert Into Temp_Debug Values('@New_Bin_On_Hand',Convert(Varchar(100),@New_Bin_On_Hand))  	

	--> Calculate Product on hand diff
	SELECT @Prev_On_Hand_Bin = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID

--Insert Into Temp_Debug Values('@Prev_On_Hand_Bin',Convert(Varchar(100),@Prev_On_Hand_Bin))  	

	SELECT @On_Hand_Diff = @New_Bin_On_Hand - @Prev_On_Hand_Bin
	SELECT @New_On_Hand = @Prev_On_Hand + @On_Hand_Diff
	
--Insert Into Temp_Debug Values('@On_Hand_Diff',Convert(Varchar(100),@On_Hand_Diff))  	
--Insert Into Temp_Debug Values('@New_On_Hand',Convert(Varchar(100),@New_On_Hand))  	

	
	--Use these to calculate the inventory GL changes
	--Consignment stock must not be taken into consideration for this calulation
	--Consignment stock that is out at customers must be taken into consideration. This might be consignment stock.
	SET @Prev_On_Hand_Adj = @Prev_On_Hand + (@StockOffSite - @ConsignmentStock)
	SET @New_On_Hand_Adj = @New_On_Hand + (@StockOffSite - @ConsignmentStock)
	
--Insert Into Temp_Debug Values('@Prev_On_Hand_Adj',Convert(Varchar(100),@Prev_On_Hand_Adj))  	
--Insert Into Temp_Debug Values('@New_On_Hand_Adj',Convert(Varchar(100),@New_On_Hand_Adj))  	
	
	--Update Bin Qty
	IF @On_Hand_Diff <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
			@ProductID,		--@ProductID int,
			@ProductBinID,	--@ProductBinID int,
    		@On_Hand_Diff,	--@Qty decimal(9,3)
    		'STOCK ADJ',	--@Source varchar(10),
    		0,				--@Batch_No
    		@UserID,		--@UserID int,
    		@CompanyID		--@CompanyID int
	END	
	
	--V6.2 RL Left in here for now
	--I need to check if this get updated anywhere else in the system
	SET @New_Job_Reserved =  @Prev_Job_Reserved
	SET	@New_Sales_Order_Reserved = @Prev_Sales_Order_Reserved
    SET @New_Quote_Reserved = @Prev_Quote_Reserved

    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
       @Prev_On_Hand_Adj <> @New_On_Hand_Adj       
		BEGIN

            SET @Diff_On_Hand = 0
            SET @Diff_Value = 0

            ------------------------------------------------------------
            --> Assign Qty Adjustment Type
            ------------------------------------------------------------
            IF @Prev_On_Hand_Adj <> @New_On_Hand_Adj
                BEGIN
                    SET @Diff_On_Hand = @New_On_Hand_Adj - @Prev_On_Hand_Adj

                    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_Adj
                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_Adj <> @New_On_Hand_Adj 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_Adj) - (@Prev_Average_Cost * @Prev_On_Hand_Adj), 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_Adj) - (@Prev_Last_Cost * @Prev_On_Hand_Adj), 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,
        			Lup_AP_Product_Bins_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,
        			@ProductBinID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO
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
--V6.2	RL		:2015-11-29 - Added Product Bins
----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Filtered_Products]
    (
       @CompanyID		int = -1,
       @FilterType		int = -1,
       @FilterValue		int = -1,
       @Criteria1		varchar(100) = '',
       @Criteria2		varchar(100) = '',
       @Criteria3		varchar(100) = '',
       @chkQtyOnHand	tinyint = 0
    )

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], ' 
    --Product Bins
    SET @SQL = @SQL + ' p.On_Hand as [Total On Hand], '
    SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Consignment Stock], '
    SET @SQL = @SQL + ' pb.Lup_AP_Product_Bins_ID as [BinID], '
    SET @SQL = @SQL + ' pb.Description as [Bin], '
    SET @SQL = @SQL + ' b.On_Hand as [On Hand], '
    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_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 + ' 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(p.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 '
    --> Product Bins
    SET @SQL = @SQL + ' LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '     ON p.AP_Products_ID = b.AP_Products_ID '
    SET @SQL = @SQL + ' LEFT OUTER JOIN Lup_AP_Product_Bins pb '
    SET @SQL = @SQL + '     ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_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'
	ELSE
	IF @FilterType = 10 --> Bin
		SET @SQL = @SQL + ' AND pb.Lup_AP_Product_Bins_ID = ' + Convert(Varchar(10), @FilterValue) 
		
	IF @chkQtyOnHand = 1
	BEGIN
		SET @SQL = @SQL + ' AND b.On_Hand <> 0'
		SET @SQL = @SQL + ' AND p.On_Hand <> 0'
	END

    SET @SQL = @SQL + ' Order By p.Description, pb.Description '
    
    EXEC (@SQL)

SET NOCOUNT OFF
GO
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
--V6.2 RL	2015-11-29	:Removed Job Reserved, Sales Order Reserved and Quote Reserved
--						 These values are calculation based on active transactions and not the what is in the AP_Products table
--V6.2 RL	2015-11-29	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Update_Adjusted_Inventory_Details_Split_Types]
    (
    	@ProductID int,
    	@New_Last_Cost money,
        @New_Average_Cost money,
        @ProductBinID int,
    	@New_Bin_On_Hand decimal(9,3), --From V6.2 This is the bin on hand qty
    	@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),
	    	@New_Job_Reserved decimal(9,3),
	    	@New_Sales_Order_Reserved decimal(9,3),
	    	@New_Quote_Reserved 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),
            @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int,
            @Batch_No int           


    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()
    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    SET @Batch_No = 0

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

	--> Calculate Product on hand diff
	SELECT @Bin_Prev_On_Hand = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @On_Hand_Diff = @New_Bin_On_Hand - @Bin_Prev_On_Hand
	SELECT @New_On_Hand = @Prev_On_Hand + @On_Hand_Diff
	
	--Update Bin Qty
	IF @On_Hand_Diff <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
		@ProductID,--@ProductID int,
        @ProductBinID,--@ProductBinID int,
    	@On_Hand_Diff,--@Qty decimal(9,3)
    	'STOCK ADJ',--@Source varchar(10),
    	0,--@Batch_No
    	@UserID,--@UserID int,
    	@CompanyID--@CompanyID int
	END	
	
	--V6.2 RL Left in here for now
	--I need to check if this get updated anywhere else in the system
	SET @New_Job_Reserved =  @Prev_Job_Reserved
	SET	@New_Sales_Order_Reserved = @Prev_Sales_Order_Reserved
    SET @New_Quote_Reserved = @Prev_Quote_Reserved


    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,
        			Lup_AP_Product_Bins_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,
        			@ProductBinID
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Clear_Product_Catalog_Non_Stock]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Clear_Product_Catalog_Non_Stock]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Clear_Product_Catalog_Non_Stock
--Purpose       :CLEAR On Hand for all Non-Stock Products in Catalog
--Functionality :
--Date          :2009/04/30
--Authors       :TB
--MODS          :
--RL	V6.0	2014-12-05	:Added Product Audit Trail
--V6.2 RL	2015-11-29	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Clear_Product_Catalog_Non_Stock]
    (
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProductID				int,
            @ProductCode			varchar(20),
    		@User_Name				varchar(40),
            @LastCost				money,
            @AverageCost			money,
            @StandardCost			money,
            @OnHand					decimal(9,3),
            @AdjustmentType			tinyint,
            @AdjustDate				datetime,
            @Note					varchar(70),
            @RetCode				int,
            @Lup_AP_Product_Bins_ID int,
            @OppositeQty			decimal(9,3)


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


    SET @RetCode = 0
    SET @AdjustmentType = 1    --Intialize as 'Adjustment' type
    SET @AdjustDate = getdate()
    SET @Note = LEFT('Non-Stock Qty Adjust by ' + @User_Name, 70)


    ------------------------------------------------------------------------------
    --> ZERO the Stock On Hand
    ------------------------------------------------------------------------------
	DECLARE Product_Cursor CURSOR FOR
        (
            SELECT p.AP_Products_ID,
                   p.Product_Code,
                   p.Last_Cost,
                   p.Average_Cost,
                   b.On_Hand,
                   b.Lup_AP_Product_Bins_ID
            FROM AP_Products p
				LEFT OUTER JOIN AP_Products_Bins b
					On p.AP_Products_ID = b.AP_Products_ID
            WHERE p.AW_User_Companies_ID =  @CompanyID AND
                  p.Slu_AW_YesNo_Non_Stock_Item = 1 AND
                  b.On_Hand <> 0
        )

	OPEN Product_Cursor

    	FETCH NEXT FROM Product_Cursor 
    	INTO
            @ProductID,
            @ProductCode,
            @LastCost,
            @AverageCost,
        	@OnHand,
        	@Lup_AP_Product_Bins_ID

    	WHILE @@FETCH_STATUS = 0
    	BEGIN

            UPDATE AP_Products
            SET On_Hand = 0,
				[User_ID] = @UserID            
            WHERE AP_Products_ID =  @ProductID
            AND On_Hand <> 0

			--Update Bin Qty
			IF @OnHand <> 0
			BEGIN
				SET @OppositeQty = @OnHand * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,					--@ProductID int,
					@Lup_AP_Product_Bins_ID,	--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'STOCK ADJ',				--@Source varchar(10),
    				0,							--@Batch_No
    				@UserID,					--@UserID int,
    				@CompanyID					--@CompanyID int
			END	

        	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,
		        	Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@LastCost,
                    @AverageCost,
        			@OnHand,
        		    0,
        			0,
        		    0,
        			@LastCost,
                    @AverageCost,
        			0,
        			0 ,
        			0,
        			0,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID,
        			@Lup_AP_Product_Bins_ID
                )

            SELECT @RetCode = SCOPE_IDENTITY()
    
    
        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @ProductCode,
                @LastCost,
                @AverageCost,
            	@OnHand,
        		@Lup_AP_Product_Bins_ID

        END
    	
	CLOSE Product_Cursor

	DEALLOCATE Product_Cursor


RETURN @RetCode


SET NOCOUNT OFF
GO
--GL Transaction Types for Consignment
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AB_Transaction_Types
	WHERE [Description] = 'Accounts Consignment - Invoice'
) 
BEGIN

	INSERT Sys_AB_Transaction_Types
	(	
		[Description], 
		Transaction_Code, 
		Sys_AB_Transaction_Categories_ID
	)
	VALUES
	(
		'Accounts Consignment - Invoice',
		'AC Invoice',
		2
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AB_Transaction_Types
	WHERE [Description] = 'Accounts Consignment - Refund'
) 
BEGIN

	INSERT Sys_AB_Transaction_Types
	(	
		[Description], 
		Transaction_Code, 
		Sys_AB_Transaction_Categories_ID
	)
	VALUES
	(
		'Accounts Consignment - Refund',
		'AC Refund',
		2
	)
END
GO
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
--V6.2 RL	2015-11-29	:Added Product Bins
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Inventory_Details]
    (
    	@ProductID int,
    	@ProductBinID int
    )
AS

SET NOCOUNT ON

    SELECT
        p.AP_Products_ID AS [ID],
        p.[Description] AS [Description],
        p.Last_Cost AS [Last Cost],
        p.Average_Cost AS [Ave Cost],
        p.On_Hand AS [Total On Hand],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Consignment Stock],
        b.On_Hand AS [On Hand],
        b.Lup_AP_Product_Bins_ID AS [BinID],
        pb.[Description] AS [Bin],
        --Job_Reserved AS [Job Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Reserved], 
        --Sales_Order_Reserved AS [S/O Reserved],
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Reserved], 
        --Quote_Reserved AS [Quote Reserved]
        CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Reserved]
    FROM AP_Products p
		LEFT OUTER JOIN AP_Products_Bins b
			ON p.AP_Products_ID = b.AP_Products_ID
		Left Outer Join Lup_AP_Product_Bins pb
			ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID	
    WHERE p.AP_Products_ID = @ProductID
    AND b.Lup_AP_Product_Bins_ID = @ProductBinID

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

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

AS

SET NOCOUNT ON

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

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

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

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



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

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

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

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

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

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

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

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

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


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

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


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

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

				END
		END


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

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

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

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

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

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


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

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

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

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

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

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

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

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


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

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

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

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

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

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

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

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

					SELECT * FROM @POS_Products_Temp Order By UniqueID
				END
		END


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

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

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


--> Returns an EMPTY rs
    ELSE
    IF @SearchType = 5
        BEGIN
        	SELECT 
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.Last_Cost AS [Last Cost], 
                0 as [Standard Discount],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
        		dbo.fn_AP_Get_Sales_Promotion_Product_ID(p.AP_Products_ID, getdate()) as [PromoProductID],
        		p.Average_Cost AS [Avg Cost], 
        		CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [Gross Margin],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
        		p.Pack_Size AS [Qty],
                0 as [Discount %],
                0 as [Discount],
        		p.AP_Products_ID as [ID],
        		p.Lup_AP_Product_Types_ID as [TypeID],
        		tc.Tax_Rate as [Tax Rate], 
                p.Pack_Mass AS [Pack Mass], 
        		p.Pack_Volume AS [Pack Volume], 
        		p.On_Hand AS [On Hand], 
        		p.Slu_AW_YesNo_Edit_Price AS [Edit Price], 
        		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount], 
        		p.Keywords as [Keywords],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved],
                CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
                p.AW_User_Companies_ID AS [CompanyID],
                p.Slu_AW_Active_ID AS [Active],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
--                p.Slu_AW_YesNo_Hide_Remote AS [HideRemote],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Average_Cost)) as [Average Margin],
                ISNULL(p.Max_Discount_Perc, 0) AS [MinGPPerc],
                p.Slu_AW_YesNo_Max_Discount_Perc AS [UseMinGPPerc],
                CONVERT(money, dbo.GetGrossContribution(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Last_Cost)) as [GrossProfit],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Standard_Cost AS [Std Cost],
                CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), Standard_Cost)) as [Standard Margin],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 9
        END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.0	RL	2014-05-13	:Inventory Adjustment is always done useing Last Cost??????????????????????????????????????????
--						 Should it not be done depending on the system option setup of Average Cost, Last Cost or Standard Cost
--V6.2	RL		:2015-12-01	:Product Bin qty changes
--------------------------------------------------------------------------------

CREATE PROCEDURE [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),
            @AP_Products_Bins_History_ID int,
            @Batch_No int,
            @ConsignmentStock    decimal(9,3),
			@ProductOffSite	decimal(9,3)       


    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
    
--Insert Into Temp_Debug Values('***Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('***Prev_Last_Cost',Convert(Varchar(100),@Prev_Last_Cost))   	
--Insert Into Temp_Debug Values('***Prev_Average_Cost',Convert(Varchar(100),@Prev_Average_Cost))   	

--Insert Into Temp_Debug Values('New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('Qty',Convert(Varchar(100),@Qty))

		SET @ProductOffSite = dbo.fn_AP_Get_Products_Out_On_Consignment(@ProductID)

--Insert Into Temp_Debug Values('***ProductOffSite',Convert(Varchar(100),@ProductOffSite))

    	SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID),0)
    	
--Insert Into Temp_Debug Values('***ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))

--Insert Into Temp_Debug Values('***New_On_Hand',Convert(Varchar(100),@New_On_Hand)) 
   	
    	SET @Qty = (@New_On_Hand) - (@Prev_On_Hand)
    	
--Insert Into Temp_Debug Values('***Qty',Convert(Varchar(100),@Qty)) 
   	
    	SET @New_On_Hand = (@New_On_Hand) - (@ConsignmentStock - @ProductOffSite)

--Insert Into Temp_Debug Values('***New_On_Hand',Convert(Varchar(100),@New_On_Hand))     	
    	
--Insert Into Temp_Debug Values('1Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('1ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))
--Insert Into Temp_Debug Values('1New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('1Qty',Convert(Varchar(100),@Qty))
    	    
    	--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
    	--Consignment stock is not GRV'd stock
		IF @Note = 'Consignment Returned - No Affect On Average Cost!!!!'
		BEGIN	
			--Need to take qty in to consideration here because fn_AP_Get_Consignment_Stock_Qty retrieves from 
			--AO_GRV_Details which has already been updated in calling procedure 
			SELECT @Prev_On_Hand = (@Prev_On_Hand ) - (@ConsignmentStock - @ProductOffSite) - (@Qty * -1)		
			--SET @Prev_On_Hand = @Prev_On_Hand - (@Qty * -1)		
		END
		ELSE
		BEGIN
			SELECT @Prev_On_Hand = (@Prev_On_Hand ) - (@ConsignmentStock - @ProductOffSite)
			--SET @Prev_On_Hand = @Prev_On_Hand
		END
		    	
--Insert Into Temp_Debug Values('***Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))     	
		    	
--Insert Into Temp_Debug Values('2Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand))   	
--Insert Into Temp_Debug Values('2ConsignmentStock',Convert(Varchar(100),@ConsignmentStock))
--Insert Into Temp_Debug Values('2New_On_Hand',Convert(Varchar(100),@New_On_Hand))
--Insert Into Temp_Debug Values('2Qty',Convert(Varchar(100),@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
	    SET @AP_Products_Bins_History_ID = 0
		SET @Batch_No = 0

		--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
		--date the products were received and not the date it was captured.
		SELECT @GLTranDate = Date_Received
		FROM AO_GRV
		WHERE AO_GRV_ID = @GRV_ID

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

		SET @New_Average_Cost = @Prev_Average_Cost

--Insert Into Temp_Debug Values('***Prev_Average_Cost',Convert(Varchar(100),@Prev_Average_Cost))     	
--Insert Into Temp_Debug Values('***New_Average_Cost',Convert(Varchar(100),@New_Average_Cost))     	

        --> 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
                        --cONSIGNMENT
                        --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
                    ELSE
                    BEGIN
						--RL V6.2 2015-05-27
						--@New_Average_Cost Equal NULL if New Qty = 0                   
						SET @New_Average_Cost = @New_Last_Cost
                    END                   
            END
        ------------------------------------------------------------------------
--Insert Into Temp_Debug Values('***@New_Average_Cost',Convert(Varchar(100),@New_Average_Cost))
--Insert Into Temp_Debug Values('***@Note',Convert(Varchar(100),@Note))
--Insert Into Temp_Debug Values('***@Qty',Convert(Varchar(100),@Qty))


		--RL V6.2	2016-05-01
		--If Last Cost and Average Cost was triggered by Consignment Stock returned
		--It should not affect the last cost and average cost!!!!!!!!!!!!!!!
		IF ( (@Note = 'Consignment Returned - No Affect On Average Cost!!!!') AND
			(@Qty < 0) )
		BEGIN
    		UPDATE AP_Products
			SET On_Hand = On_Hand + @Qty,
				[User_ID] = @UserID
    		WHERE AP_Products_ID = @ProductID		
--Insert Into Temp_Debug Values('In Qty Update',@Note)
		END
		ELSE
		BEGIN
    		UPDATE AP_Products
			SET Last_Cost = @New_Last_Cost,
				Average_Cost = @New_Average_Cost,
				--On_Hand = @New_On_Hand + @ConsignmentStock,
				On_Hand = On_Hand + @Qty, --+ @ConsignmentStock,
				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
--Insert Into Temp_Debug Values('In NORMAL Update',@Note)
		END
		--Update Bin Qty
		IF @Qty <> 0
		BEGIN
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,		--@ProductID int,
				1,				--@ProductBinID int,
    			@Qty,			--@Qty decimal(9,3)
    			'ProdUpdate',	--@Source varchar(10),
    			0,				--@Batch_No
    			@UserID,		--@UserID int,
    			@CompanyID		--@CompanyID int
		END	
					
        --> 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

						--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
						--date the products were received and not the date it was captured.
                        --> The above should match the Accounting Period of the GRV !!
                        --SET @Month = DATEPART(mm, getdate())
                        --SET @Year = DATEPART(yy, getdate())
                        SET @Month = DATEPART(mm, @GLTranDate)
                        SET @Year = DATEPART(yy, @GLTranDate)

                        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
					--RL V6.0 It will never go in here!!!!!
                    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,
            			Lup_AP_Product_Bins_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,
            			1 --Defaulted to 1
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    END 			


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Product_Bin_Consignment_CHK]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Product_Bin_Consignment_CHK]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Product_Bin_Consignment_CHK
--Purpose       :Check to see if a GRV or CRV on a product does not push the 
--				 Consignment or Bin into a negative
--Date          :2015-12-01
--Authors       :RL
--Version       :6.2
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Product_Bin_Consignment_CHK]
    (	
    	@AP_Products_ID int,
    	@Qty decimal(9,3),
    	@BinCHK tinyint,
    	@ConsignmentCHK tinyint,
    	@ReturnMsg varchar(8000) Output
    )
AS

SET NOCOUNT ON

	DECLARE @On_Hand Decimal(9,3),
            @Bin_On_Hand Decimal(9,3),
            @Consignment_Stock Decimal(9,3),            
            @Product_Code varchar(20),
            @Product_Description varchar(50),
            @Available_To_Return Decimal(9,3),
            @BinEnabled varchar(10)

	SET @ReturnMsg = ''
	SET @On_Hand = 0
	SET @Bin_On_Hand = 0
	SET @Consignment_Stock = 0
	
	SELECT  @Product_Code = ISNULL(Product_Code,''),
			@Product_Description = ISNULL([Description],''),
			@On_Hand = On_Hand
	FROM AP_Products
	WHERE AP_Products_ID = @AP_Products_ID
	
	IF @BinCHK = 1
	BEGIN
	
		SET @BinEnabled = '0'
		SELECT @BinEnabled = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkEnableProductBins'
		AND Control_Index = 0
	
		IF @BinEnabled = '1'
		BEGIN
			SET @Bin_On_Hand = 0
			
			SELECT @Bin_On_Hand = On_Hand
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @AP_Products_ID
			AND Lup_AP_Product_Bins_ID = 1
			
			IF @Qty > @Bin_On_Hand
			BEGIN  --
				Select @ReturnMsg = @ReturnMsg + 'Product ' + @Product_Code + ' - ' + @Product_Description + ' exceeds default bin quantity of ' + '' + CONVERT(varchar(10),@Bin_On_Hand) + '' + '
'
			END
		END
	END

	IF @ConsignmentCHK = 1
	BEGIN
		SET @Consignment_Stock = 0
		SELECT @Consignment_Stock = dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID)

		IF @Consignment_Stock > 0
		BEGIN
	
			SELECT @Available_To_Return = @On_Hand - @Consignment_Stock
			IF @Consignment_Stock <> 0
			BEGIN
				IF @Available_To_Return < @Qty
				BEGIN
					Select @ReturnMsg = @ReturnMsg + 'Product ' + @Product_Code + ' - ' + @Product_Description + ' is atempting to return consignment stock.
On Hand - ' + '' + CONVERT(varchar(10),@On_Hand) + '' + ' Consignment Stock ' + '' + CONVERT(varchar(10),@Consignment_Stock) + '' + ' Available to return ' + '' + CONVERT(varchar(10),@Available_To_Return) + '' + '
'
				END
			END	
		END
	END
	
SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Stock_Take_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Stock_Take_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AP_Stock_Take_Lups
--Purpose       :Product Stock Take Lookups
--Date          :2009/02/15
--Authors       :TB
--MODS          :
--2004.4.4      :30/04/09 - Added Choice 10 - User
--V6.2	RL	2015-12-01	:Added Product Bins
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Stock_Take_Lups]
    (
    	@Choice int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

    --> 1 - Product Types
    	IF @Choice = 1
    		SELECT Lup_AP_Product_Types_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 2 - Product Groups
    	ELSE 
    	IF @Choice = 2	
    		SELECT Lup_AP_Product_Groups_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 3 - Product Departments
    	ELSE 
    	IF @Choice = 3	
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Departments	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 4 - Product Locations
    	ELSE 
    	IF @Choice = 4	
    		SELECT Lup_AP_Product_Locations_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Locations	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 5 - Product Manufacturers
    	ELSE 
    	IF @Choice = 5
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 6 - Default Supplier
    	ELSE 
    	IF @Choice = 6
    		SELECT AO_Suppliers_ID AS [ID], 
    		[Supplier_Name] AS [Supplier_Name] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Supplier_Name]
    
    --> 7 - Purchase Categories
    	ELSE 
    	IF @Choice = 7	
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    		[Description] AS [Description] 
    		FROM Lup_AP_Purchase_Categories	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

    --> Years
        ELSE
        IF @Choice = 8 
        	SELECT Slu_AW_Years_ID AS [ID], 
            [Description] AS [Year] 
        	FROM Slu_AW_Years
        
    --> Months
        ELSE 
        IF @Choice = 9
        	SELECT Slu_AW_Months_ID AS [ID], 
            [Description] AS [Month] 
        	FROM Slu_AW_Months

	--> User
    	ELSE 
    	IF @Choice = 10
            SELECT AW_Users_ID AS [ID],
                   ISNULL(UserName, '') AS [User]
            FROM AW_Users
            ORDER BY [User]

	--> Product Bins
    	ELSE 
    	IF @Choice = 11
            SELECT Lup_AP_Product_Bins_ID AS [ID],
                   [Description] AS [Description] 
            FROM Lup_AP_Product_Bins
            ORDER BY [Description]

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Stock_Take]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Stock_Take]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Stock_Take
--Purpose       :
--Date          :2009/02/19
--Authors       :TB
--MODS          :
--2004.4.4      :30/04/09 - Added @UserID input parameter to assign ID of editing user
--V6.2	RL	2015-12-01	:Added Product Bins
----V6.3	RL	2017-02-01	:Update On_Hand_Calc = @TotalCount and Variance_Calc = @Variance for post adjustments
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Stock_Take]
	(
        @StockTakeID int,
        @ProductID int,
        @BinID int,
        @Count1 decimal(9, 3),
        @Count2 decimal(9, 3),
        @Count3 decimal(9, 3),
        @TotalCount decimal(12, 3),
        @Variance decimal(12, 3),
        @UserID int
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    IF EXISTS
        (
            SELECT AP_Products_Stock_Takes_ID
            FROM AP_Products_Stock_Takes
            WHERE AP_Products_Stock_Takes_ID = @StockTakeID AND
                  AP_Products_ID = @ProductID AND
                  Lup_AP_Product_Bins_ID = @BinID
        )
        BEGIN
            UPDATE AP_Products_Stock_Takes
            SET Count1 = @Count1,
                Count2 = @Count2,
                Count3 = @Count3,
                Total_Count = @TotalCount,
                Variance = @Variance,
                User_ID = @UserID,
                Variance_Calc = @Variance,
                On_Hand_Calc = @TotalCount
            WHERE AP_Products_Stock_Takes_ID = @StockTakeID AND
                  AP_Products_ID = @ProductID AND
                  Lup_AP_Product_Bins_ID = @BinID

            SET @ReturnValue = 1

        END


RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Stock_Take_Filters]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Stock_Take_Filters]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Stock_Take_Filters
--Purpose       :Filters Products from Stock Takes
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2009/02/19
--Authors       :TB
--MODS          :
--2004.4.4      :29/04/09 - Added @ProcedureID input parameter !!!!
--              :30/04/09 - Added User_ID field to assign ID of editing user
--              :30/04/09 - Added also to include fetch items with NON-ZERO COUNT if @OnHandOnly = 1
--V6.2	RL	2015-12-01	:Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Filter_Stock_Take_Filters]
	(
    	@CompanyID int,
    	@ProcedureID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
        @LocationID int = -1,
        @PurchaseID int = -1,
        @BinID int = -1,
        @OnHandOnly tinyint,
        @Sort tinyint,
        @NonStock tinyint,
        @VarianceOnly tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @SQL varchar(8000)

	SET @Filter = ''
    SET @SQL = ''


    SET @Filter = ' WHERE ' + ' st.AP_Stock_Take_Procedures_ID = ' +
                                convert(varchar(20), @ProcedureID)

    --> Products_Suppliers
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
		END

    --> Purchase Category
	IF @PurchaseID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseID)
		END

    --> Product Bins
	IF @BinID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' st.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND st.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END

	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' st.AP_Products_Stock_Takes_ID AS [ID], '
        SET @SQL = @SQL + ' st.AP_Stock_Take_Procedures_ID AS [StockTakeProcedureID], '
        SET @SQL = @SQL + ' st.AP_Products_ID AS [Product_ID], '
        SET @SQL = @SQL + ' ISNULL(p.[Description], '''') AS [Product], '
        SET @SQL = @SQL + ' ISNULL(p.Product_Code, '''') AS [Code], '
        SET @SQL = @SQL + ' st.Total_On_Hand AS [Total On Hand], '
        SET @SQL = @SQL + ' st.Consignment_Qty AS [Cons Qty], '                        
        SET @SQL = @SQL + ' ISNULL(b.[Description], '''') AS [Bin], '
        SET @SQL = @SQL + ' ISNULL(st.Lup_AP_Product_Bins_ID, 1) AS [BinID], '
        SET @SQL = @SQL + ' st.Count1 AS [Count1], '
        SET @SQL = @SQL + ' st.Count2 AS [Count2], '
        SET @SQL = @SQL + ' st.Count3 AS [Count3], '
        SET @SQL = @SQL + ' st.Total_Count AS [Total], '
        SET @SQL = @SQL + ' st.On_Hand AS [On Hand], '
        SET @SQL = @SQL + ' st.Variance AS [Variance], '
        SET @SQL = @SQL + ' st.Unit_Cost AS [Unit Cost], '        
        SET @SQL = @SQL + ' st.User_ID AS [User] '
        SET @SQL = @SQL + ' FROM AP_Products_Stock_Takes st '
        SET @SQL = @SQL + '     LEFT JOIN AP_Products p '
        SET @SQL = @SQL + '         ON st.AP_Products_ID = p.AP_Products_ID '
        SET @SQL = @SQL + '     LEFT OUTER JOIN LUP_AP_Product_Bins b '
        SET @SQL = @SQL + '         ON st.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID '        
        SET @SQL = @SQL + @Filter


        IF @OnHandOnly = 1
            BEGIN
                SET @sql = @sql + ' AND (st.On_Hand <> 0 OR st.Total_Count <> 0) '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @VarianceOnly = 1
            BEGIN
                SET @sql = @sql + ' AND st.Variance <> 0 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY p.Product_Code, b.[Description] '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY p.[Description], b.[Description] '
            END



		EXEC (@SQL)

	END



SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Stock_Take_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Stock_Take_Insert
--Purpose       :Inserts Ad Hoc Stock Take into
--Tables        :    AP_Stock_Take_Procedures AND AP_Products_Stock_Takes
--Date          :2002/02/14
--Authors       :TB
--MODS          :21/04/02 - Insert 0 into Count1 not 'On_Hand, '
--              :24/04/02 - Removed Discount & Commission parameters
--              :15/08/03 - Switched to NEW AP_Stock_Take_Procedures from
--              :           AW_Period_Procedures because of table cluttering
--2004.4.3      :15/02/09 - Updated with the latest Stock Valuation costing methods
--              :15/02/09 - Reworked with new table definitions
--2004.4.4      :02/05/09 - Added ISNULL validation of Costs and On Hand before insert - TCWIT
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Insert]
	(
    	@UserID int,
    	@CompanyID int,
    	@Description varchar(500),
    	@ManufacturerID int = -1,
    	@DepartmentID int = -1,
    	@LocationID int = -1,
    	@TypeID int = -1,
    	@ProductGroupID int = -1,
    	@SupplierID int = -1,
    	@BinID int = -1
	)

AS

SET NOCOUNT ON

	DECLARE @ProcedureID int,
            @Filter varchar(6000),
            @SQL varchar(6000),
            @StockValuation money,
            @ValuationMethod smallint


	SET @Filter = ''

    --> Company
	IF @CompanyID > 0 
		BEGIN
            SET @Filter = ' WHERE p.AW_User_Companies_ID = ' + 
                            CONVERT(varchar(20), @CompanyID)
        END

    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Manufacturers_ID = ' +
                                CONVERT(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                CONVERT(varchar(20), @ManufacturerID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Departments_ID = ' +
                                CONVERT(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                CONVERT(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Locations_ID = ' +
                                CONVERT(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                CONVERT(varchar(20), @LocationID)
    	END
    --> Type
	IF @TypeID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Types_ID = ' +
                                CONVERT(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                CONVERT(varchar(20), @TypeID)
		END
    --> Product Group
	IF @ProductGroupID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Groups_ID = ' +
                                CONVERT(varchar(20), @ProductGroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                CONVERT(varchar(20), @ProductGroupID)
		END
    --> Default Supplier
	IF @SupplierID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Default_Supplier_ID = ' +
                                CONVERT(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                CONVERT(varchar(20), @SupplierID)
		END
    --> Product Bin
	IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END


	INSERT AP_Stock_Take_Procedures
        (
            [Description],
            [Procedure_Date],
            [Stock_Valuation],
            [User_ID],
            AW_User_Companies_ID
        )
    VALUES
        (
            @Description,
            getdate(),
            0,
            @UserID,
            @CompanyID
        )

	SELECT @ProcedureID = Scope_Identity()


    --------------------------------------------------------
    --> Get Primary Costing Method
    --------------------------------------------------------
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID
    --------------------------------------------------------


	SET @SQL = 'INSERT AP_Products_Stock_Takes ('
    SET @SQL = @SQL + 'AP_Products_ID, '
    SET @SQL = @SQL + 'Lup_AP_Product_Bins_ID, '
    SET @SQL = @SQL + 'AP_Stock_Take_Procedures_ID, '
    SET @SQL = @SQL + 'Count1, '
    SET @SQL = @SQL + 'Count2, '
    SET @SQL = @SQL + 'Count3, '
    SET @SQL = @SQL + 'Total_Count, '
    SET @SQL = @SQL + 'Unit_Cost, '
    SET @SQL = @SQL + 'On_Hand, '
    SET @SQL = @SQL + 'Variance, '
    SET @SQL = @SQL + 'Total_On_Hand, '
    SET @SQL = @SQL + 'Consignment_Qty, ' 
    SET @SQL = @SQL + 'On_Hand_Calc, '     
    

       
    SET @SQL = @SQL + 'AW_User_Companies_ID, '
    SET @SQL = @SQL + 'User_ID'
    SET @SQL = @SQL + ') '

    SET @SQL = @SQL + 'SELECT p.AP_Products_ID, '
    SET @SQL = @SQL + 'b.Lup_AP_Product_Bins_ID, '
    SET @SQL = @SQL + CONVERT(varchar(10), @ProcedureID) + ', ' 
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '
    SET @SQL = @SQL + '0, '

--     IF @ValuationMethod = 0
--         BEGIN
--             SET @SQL = @SQL + 'Average_Cost, '
--         END
--     ELSE
--     IF @ValuationMethod = 1
--         BEGIN
--             SET @SQL = @SQL + 'Last_Cost, '
--         END
--     ELSE
--     IF @ValuationMethod = 2
--         BEGIN
--             SET @SQL = @SQL + 'Standard_Cost, '
--         END
-- 
--     SET @SQL = @SQL + 'On_Hand, '
--     SET @SQL = @SQL + '(On_Hand * -1), '

    --2004.4.4 - Added ISNULL validation of Costs and On Hand - TCWIT
    IF @ValuationMethod = 0
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Average_Cost, 0), '
        END
    ELSE
    IF @ValuationMethod = 1
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Last_Cost, 0), '
        END
    ELSE
    IF @ValuationMethod = 2
        BEGIN
            SET @SQL = @SQL + 'ISNULL(p.Standard_Cost, 0), '
        END

    SET @SQL = @SQL + 'ISNULL(b.On_Hand, 0), '				--V6.2 Bin On Hand Used
    SET @SQL = @SQL + '(ISNULL(b.On_Hand, 0) * -1), '		--V6.2 Bin On Hand Used
    SET @SQL = @SQL + 'ISNULL(p.On_Hand, 0), '				
	SET @SQL = @SQL + 'ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0), '				    

	SET @SQL = @SQL + '		CASE '
	SET @SQL = @SQL + '			WHEN ( ISNULL(p.On_Hand, 0) - ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0) ) < ISNULL(p.On_Hand, 0) Then 0 '
	SET @SQL = @SQL + '			ELSE ( ISNULL(p.On_Hand, 0) - ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID),0) )'
	SET @SQL = @SQL + '		END, '


    SET @SQL = @SQL + CONVERT(varchar(10),@CompanyID) + ', '
    SET @SQL = @SQL + CONVERT(varchar(10),@UserID) + ' '
    SET @SQL = @SQL + 'FROM AP_Products p'
    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'   
    SET @SQL = @SQL + @Filter


	EXEC (@SQL)
	--Select @SQL

	UPDATE AP_Products_Stock_Takes
	SET Variance_Calc = Variance + Consignment_Qty
	WHERE AP_Stock_Take_Procedures_ID = @ProcedureID

    IF @ValuationMethod = 0
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Average_Cost, 0) * ISNULL(pst.On_Hand, 0) )	--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Average_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )	--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    ELSE
    IF @ValuationMethod = 1
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Last_Cost, 0) * ISNULL(pst.On_Hand, 0) )		--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Last_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )		--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    ELSE
    IF @ValuationMethod = 2
        BEGIN
        	--SELECT @StockValuation = SUM( ISNULL(p.Standard_Cost, 0) * ISNULL(pst.On_Hand, 0) )	--V6.2 Bin On Hand Used
        	SELECT @StockValuation = SUM( ISNULL(p.Standard_Cost, 0) * ISNULL(pst.On_Hand_Calc, 0) )	--V6.2 Bin On Hand Used
        	FROM AP_Products p
                INNER JOIN AP_Products_Stock_Takes pst
                    ON pst.AP_Products_ID = p.AP_Products_ID
            WHERE pst.AP_Stock_Take_Procedures_ID = @ProcedureID
        END
    --------------------------------------------------------

    --> Update table with Stock Valuation (theoretical now)
    UPDATE AP_Stock_Take_Procedures
    SET Stock_Valuation = @StockValuation
    WHERE AP_Stock_Take_Procedures_ID = @ProcedureID



RETURN @ProcedureID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Stock_Take_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Products_Stock_Take_Select
--Purpose       :Check if Products EXIST for selected Filters before Create Stock Take
--Date          :2009/02/20
--Authors       :TB
--MODS          :
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Products_Stock_Take_Select]
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@DepartmentID int = -1,
    	@LocationID int = -1,
    	@TypeID int = -1,
    	@ProductGroupID int = -1,
    	@SupplierID int = -1,
    	@BinID int = -1
	)
AS

SET NOCOUNT ON

    DECLARE @Filter varchar(6000),
            @SQL varchar(6000)


	SET @Filter = ''


    --> Company
	IF @CompanyID > 0 
		BEGIN
            SET @Filter = ' WHERE p.AW_User_Companies_ID = ' + 
                            convert(varchar(20), @CompanyID)
        END

    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
    	END
    --> Type
	IF @TypeID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Product Group
	IF @ProductGroupID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @ProductGroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @ProductGroupID)
		END
    --> Default Supplier
	IF @SupplierID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Product Bin
	IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END


    SET @SQL = 'SELECT count(*) AS [CNT] '
    SET @SQL = @SQL + 'FROM AP_Products p'
    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
    SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'
    SET @SQL = @SQL + @Filter

	EXEC (@SQL)
	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Stock_Bins]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Stock_Bins]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Stock_Bins
--Purpose       :Retrieves Inventory Stock per Bin
--Date          :2015-12-02
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Stock_Bins]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1,
        @BinID int = -1,
        @Sort int,
        @NonStock int,
        @Option varchar(30)
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @SQL varchar(2000),
            @ValuationMethod smallint

	SET @Filter = ''
    SET @SQL = ''

    --> Get Primary Costing method
    SELECT @ValuationMethod = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
          Control_Name = 'optInventoryValuation' AND
          Control_Value = 'True' AND
          AW_User_Companies_ID = @CompanyID


		---------------------------------------------------------
		--Filter Begin
		---------------------------------------------------------
    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END
    --> PurchCat
    	IF @PurchCatID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
        	END
	    --> Product Bin
		IF @BinID  > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
			ELSE
				SET @Filter = @Filter + ' AND b.Lup_AP_Product_Bins_ID = ' +
                                convert(varchar(20), @BinID)
		END

		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END

		SET @Filter = @Filter + ' AND ' + ' b.On_Hand <> 0 '
		---------------------------------------------------------
		--Filter End
		---------------------------------------------------------


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '

		IF @Option = 'Type'
			SET @sql = @sql +
				' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Groups'
			SET @sql = @sql +
				' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Department'
			SET @sql = @sql +
				' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Supplier'
			SET @sql = @sql +
				' o.AO_Suppliers_ID AS [HeaderID], ' +
				' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
		ELSE
		IF @Option = 'Manufacturer'
			SET @sql = @sql +
				' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Location'
			SET @sql = @sql +
				' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
				' ISNULL(o.[Description], '''') AS [Filter], '
		ELSE
		IF @Option = 'Purchase Category'
			SET @sql = @sql +
				' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
				' o.[Description] AS [Filter], '

        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' l.[Description] AS [Bin], '        
        SET @SQL = @SQL + ' b.On_Hand AS [Qty], '
        
        If @ValuationMethod = 0 --Average_Cost
        Begin
			SET @SQL = @SQL + ' p.Average_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand  * p.Average_Cost AS [TotalCost], '
		End	
        If @ValuationMethod = 1 --Last_Cost
        Begin
			SET @SQL = @SQL + ' p.Last_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand * p.Last_Cost AS [TotalCost], '
		End
        If @ValuationMethod = 2 --Standard_Cost
        Begin
			SET @SQL = @SQL + ' p.Standard_Cost AS [Cost], '
			SET @SQL = @SQL + ' b.On_Hand * p.Standard_Cost AS [TotalCost], '
		End
        
        SET @SQL = @SQL + ' p.Price1_Price1 AS [Price1_Price1], '        
        SET @SQL = @SQL + ' b.On_Hand * p.Price1_Price1 AS [TotalPrice1_Price1] '        

        SET @SQL = @SQL + ' FROM AP_Products p '
	    SET @SQL = @SQL + '		LEFT OUTER JOIN AP_Products_Bins b '
		SET @SQL = @SQL + '			ON p.AP_Products_ID = b.AP_Products_ID'        
	    SET @SQL = @SQL + '		INNER JOIN Lup_AP_Product_Bins l '
		SET @SQL = @SQL + '			ON b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID'
		
		
		IF @Option = 'Type'
			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 @Option = 'Groups'
			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 @Option = 'Department'
			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 @Option = 'Supplier'
			SET @sql = @sql +
				'    LEFT JOIN AO_Suppliers o ' +
				'        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
		ELSE
		IF @Option = 'Manufacturer'
			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 @Option = 'Location'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Product_Locations o ' +
				'        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
		ELSE
		IF @Option = 'Purchase Category'
			SET @sql = @sql +
				'    LEFT JOIN Lup_AP_Purchase_Categories o ' +
				'        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
		
        SET @SQL = @SQL + @Filter


        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY l.[Description], [Filter], p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY l.[Description], [Filter], p.[Description] '
            END


    EXEC (@SQL)
--Select @SQL


SET NOCOUNT OFF	
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Products_Out_On_Consignment]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Products_Out_On_Consignment]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Products_Out_On_Consignment
--Purpose       :Returns quantity of how many units are out on Consignment
--Parameters    :
--Date          :2015/06/10
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Products_Out_On_Consignment]
	(
        @ProductID int
	)
RETURNS decimal(9,3)

AS
    BEGIN

        DECLARE @OutOnConsignmentQTY decimal(9,3)

    -------------------------------------------------------------------------------
    --Stock Out On Consignment
    -------------------------------------------------------------------------------
        SELECT @OutOnConsignmentQTY = 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 = 33 OR
              h.Sys_AW_Transaction_Types_ID = 34 OR
              h.Sys_AW_Transaction_Types_ID = 35)
              
    -------------------------------------------------------------------------------

        RETURN(@OutOnConsignmentQTY)
    
    END
GO
--Stock Bin Quantities
IF NOT EXISTS
(
	SELECT Sys_AW_Reports_ID
	FROM Sys_AW_Reports
	WHERE Report_No = '224' 
	AND	Method_Name = 'Show_StockBinQuantities'
) 

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
	(
		2,
		0,
		'Product Reports',
		'224',
		'Stock Bin Quantities',
		'Stock Bin Quantities',
		'SpSProductReports',
		'CInterface',
		'Show_StockBinQuantities'
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Bins_Update_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Bins_Update_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Products_Bins_Update_Insert
--Purpose       :maintain Product Bins
--Date          :2015-02-02
--Authors       :RL
--Mods          :
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Products_Bins_Update_Insert]
    (
    	@ProductID		int,
        @ProductBinID	int,
    	@Qty			decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Source			varchar(10),
    	@Batch_No		int,
    	@UserID			int,
    	@CompanyID		int
    )
AS

SET NOCOUNT ON

	Declare @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int

    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @Bin_Prev_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    --SET @Batch_No = 0

 	--> Calculate Product on hand diff
	SELECT @Bin_Prev_On_Hand = On_Hand
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @New_On_Hand = @Bin_Prev_On_Hand + @Qty
	
	IF @Qty <> 0
	BEGIN
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @ProductBinID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = @New_On_Hand
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @ProductBinID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@ProductBinID,
				@New_On_Hand,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		IF @Source <> ''
		BEGIN		
			--SELECT @AP_Products_Bins_History_ID = MAX(AP_Products_Bins_History_ID)
			--FROM AP_Products_Bins_History
			--WHERE AP_Products_ID = @ProductID
			
			--SELECT @Batch_No = MAX(Batch_No)
			--FROM AP_Products_Bins_History
			
			--IF @Batch_No IS NULL
			--	SET @Batch_No = 0
				
			--SET @Batch_No = @Batch_No + 1
			
			IF @AP_Products_Bins_History_ID = 0
			BEGIN
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				VALUES
				(
					@Batch_No, 
					@ProductID, 
					@ProductBinID, 
					@Bin_Prev_On_Hand, 
					@New_On_Hand, 
					1, --To_Lup_AP_Product_Bins_ID
					0, --To_Bin_Previous_On_Hand
					0, --To_Bin_New_On_Hand
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1 --Slu_AW_Active_ID
				)			
			END
			ELSE
			BEGIN			
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				SELECT
					@Batch_No, 
					@ProductID, 
					@ProductBinID, 
					@Bin_Prev_On_Hand, 
					@New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_New_On_Hand, 
					To_Bin_New_On_Hand, 
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1
				FROM AP_Products_Bins_History
				WHERE AP_Products_Bins_History_ID = @AP_Products_Bins_History_ID		
			END
		END
	END
SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Link_Select_Product_Search_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Link_Select_Product_Search_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Link_Select_Product_Search_Lups
--Purpose       :Returns a rs for the specified LUP 
--Functionality :
--Parameters    :	
--Date          :2002/02/14
--Authors       :TB
--Version       :1.0.0
--MODS:         :14/04/04 - Added ORDER BY in Option 1 and 2
--2004.3.2      :30/09/06 - Added GL Accounts in Option 9 for Product Updates
--2004.4.1      :29/09/08 - Added Purchase Category
--V6.2	RL	2015-11-16	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Link_Select_Product_Search_Lups]
    (
    	@Option int
    )

AS

SET NOCOUNT ON

    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
            ORDER BY Supplier_Name
    
    --> Manufacturer
    	ELSE 
    	IF @Option = 2
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Manufacturers
            ORDER BY [Description]
    
    --> Type
    	ELSE 
    	IF @Option = 3
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Types
    
    --> Group
    	ELSE 
    	IF @Option = 4
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Groups	
    
    --> Department
    	ELSE 
    	IF @Option = 5
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Product_Departments
    
    --> Location
    	ELSE 
    	IF @Option = 6
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Locations

    --> Active
    	ELSE 
    	IF @Option = 7
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_Active

    --> Model Types
    	ELSE 
    	IF @Option = 8
    		SELECT Lup_AP_Switch2_Types_ID AS [ID],
    		   [Description] 
    		FROM Lup_AP_Switch2_Types

    --> GL Accounts
        ELSE 
    	IF @Option = 9
        	SELECT AB_Accounts_ID AS [ID], 
               [Description]
        	FROM AB_Accounts 
        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Purchase Categories
    	ELSE 
    	IF @Option = 10
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Purchase_Categories
            ORDER BY [Description]

    --> From Bins
    	ELSE 
    	IF @Option = 11
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [From Bin]
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]
    --> To Bins
    	ELSE 
    	IF @Option = 12
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [To Bin] 
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 13
    		SELECT Lup_AP_Product_Bins_ID AS [ID], 
    			[Description] AS [Description] 
    		FROM Lup_AP_Product_Bins
            ORDER BY [Description]            

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

-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation_Select
--Purpose       :Fetch a list of Bin Allocation Batchs
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Allocation_Select]
    (
        @CompanyID int
    )

AS

SET NOCOUNT ON

    SELECT Distinct Batch_No AS [Batch_No],
           CONVERT(Varchar(20),Date_Captured,120) AS [Date]          
    FROM AP_Products_Bins_History
    WHERE AW_User_Companies_ID = 1 --@CompanyID
    AND Batch_No <> 0
    ORDER BY Batch_No DESC

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

-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_Allocation_Select_Filtered
--Purpose       :Fetch Bin Allocation Batch Details
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_Allocation_Select_Filtered]
    (
        @Batch_No	int,
        @CompanyID	int
    )

AS

SET NOCOUNT ON

    SELECT h.AP_Products_ID AS [ID],
          p.[Description] AS [Description],
          p.Product_Code AS [Code],
                    
          h.From_Bin_New_On_Hand AS [From Bin Qty],
          From_Lup_AP_Product_Bins_ID AS [From Bin],
          fb.[Description] AS [FromBin],
          fb.Email AS [From Bin Email],          
          h.From_Bin_Previous_On_Hand AS [Orig From Bin Qty],          
          
          h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand AS [Transfer],                    
          
          To_Lup_AP_Product_Bins_ID AS [To Bin],
          h.To_Bin_New_On_Hand AS [To Bin Qty],
          tb.[Description] AS [ToBin],
          tb.Email AS [To Bin Email],                    
          h.To_Bin_Previous_On_Hand AS [Orig To Bin Qty],
          
          h.From_Bin_Previous_On_Hand + h.To_Bin_Previous_On_Hand AS [All Bin Qty] ----h.On_Hand          
    FROM AP_Products_Bins_History h
		Inner Join AP_Products p
			On h.AP_Products_ID = p.AP_Products_ID
		Inner Join Lup_AP_Product_Bins fb
			On fb.Lup_AP_Product_Bins_ID = h.From_Lup_AP_Product_Bins_ID
		Inner Join Lup_AP_Product_Bins tb
			on tb.Lup_AP_Product_Bins_ID = h.To_Lup_AP_Product_Bins_ID
    WHERE h.AW_User_Companies_ID = @CompanyID
    AND Batch_No = @Batch_No
    ORDER BY [Description], h.AP_Products_ID

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_On_Hand_Bin]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_On_Hand_Bin]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AP_Get_On_Hand_Bin
--Purpose       :Gets Non-Stock field setting from a AP_Products_ID and Bin
--Date			:2016/04/08
--Authors		:RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_On_Hand_Bin]
	(
		@ProductID int,
		@ProductBinID int,
        @CompanyID int,
        @NonStock tinyint OUTPUT,
        @OnHand decimal(9, 3) OUTPUT
	)
AS

SET NOCOUNT ON

    SELECT @NonStock = Slu_AW_YesNo_Non_Stock_Item,
           @OnHand = b.On_Hand
    FROM AP_Products p
		INNER JOIN AP_Products_Bins b
			ON p.AP_Products_ID = b.AP_Products_ID
    WHERE p.AP_Products_ID = @ProductID AND
          p.AW_User_Companies_ID = @CompanyID AND
          b.Lup_AP_Product_Bins_ID = @ProductBinID

SET NOCOUNT OFF
Go
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_Product_Job_Reserved_Bin]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_Product_Job_Reserved_Bin]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_Reserved_Bin
--Purpose       :Fetch the JOB RESERVED Qty for ONE Product and Bin on ALL OPEN Jobcards
--Date          :2016/04/08
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Product_Job_Reserved_Bin]
    (
        @ProductID int,
        @ProductBinID int,
        @Reserved float OUTPUT
    )
AS

SET NOCOUNT ON

        SELECT @Reserved = 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
			  d.Lup_AP_Product_Bins_ID = @ProductBinID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
 
SET NOCOUNT OFF
GO
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 [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
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[AB_Enterprise_Management_Accounts]
--Temp tables. Get recreated in the system anyway
GO
CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
	[IS1ID] [int] NULL ,
	[IS2ID] [int] NULL ,        	
	[IS3ID] [int] NULL ,        	
	[IS4ID] [int] NULL ,
	[GLID] [int] NULL ,
	[DivisionID] [int] NULL ,
	[GroupID] [int] NULL ,
	
	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
	
	[GLDivision] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[GLGroup] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[AccountNo] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[Account] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	
	[TotalActual] [money] NULL,
	[TotalBudget] [money] NULL,
	[TotalYTDActual] [money] NULL,
	[TotalYTDBudget] [money] NULL        	
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
	(
		[AB_Enterprise_Management_Accounts_ID]
	)  ON [PRIMARY] 
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_BFWD_Inventory_On_Hand]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_BFWD_Inventory_On_Hand]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_BFWD_Inventory_On_Hand
--Purpose       :Retrieves Opening Inventory On Hand BEFORE a date
--Parameters    :
--Date          :2004/10/09
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	2014-12-05	:Added transaction type 23 - Stock Transfer to sales query
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_BFWD_Inventory_On_Hand]
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @GRV float,
                @ADJ float,
                @SALES float,
                @BFWD float

    -------------------------------------------------------------------------------
    -- GOODS RECEIVED
    -------------------------------------------------------------------------------
        SELECT @GRV = ISNULL(SUM(Qty), 0)
        FROM AO_GRV_Details
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
              ISNULL(Qty, 0) <> 0
    -------------------------------------------------------------------------------
    -- ADJUSTMENTS
    -------------------------------------------------------------------------------
        SELECT @ADJ = ISNULL(SUM(ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0)), 0)
        FROM AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
             (Sys_AP_Adjustment_Types_ID = 1 OR
              Sys_AP_Adjustment_Types_ID = 6) AND
              ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
    -------------------------------------------------------------------------------
    -- SALES
    -------------------------------------------------------------------------------
        SELECT @SALES = 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.Date_Captured < @OpeningDate AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR			--Tax Invoice
              h.Sys_AW_Transaction_Types_ID = 4 OR			--Tax Credit Note
              h.Sys_AW_Transaction_Types_ID = 23 OR			--Stock Transfer
              h.Sys_AW_Transaction_Types_ID = 33 OR			--Consignment Note
              h.Sys_AW_Transaction_Types_ID = 34 OR			--Consignment Sold
              h.Sys_AW_Transaction_Types_ID = 35 ) AND		--Consignment Returned              
              ISNULL(d.Quantity, 0) <> 0
    -------------------------------------------------------------------------------


        SET @BFWD = @GRV + @ADJ - @SALES


        RETURN(@BFWD)

    
    END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Insert_CBilling_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Insert_CBilling_Temp]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Insert_CBilling_Temp
--Functionality :INSERT daily UNSUBMITTED Centralised Sales transactions
--Parameters    :
--Date          :2005/09/29
--Authors       :TB
--MODS          :03/10/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
--2004.2.8      :03/05/06 - Added input parameters to EXCLUDE Sales Cost Prices
--              :           and Truck and Tractor SALES data from submission
--2004.3.2      :22/09/06 - Added TRUNCATE all table varchar(50) fields to LEFT(48)
--              :01/11/06 - Added EXCLUDE Lubrication SALES data from submission
--2004.3.4      :21/02/07 - Replaced @chkTruckSales tinyint input parameter with
--              :           @ExclusionsFilter varchar(250) and append to query
--              :24/03/07 - Removed all customer details from submission file
--              :           EXCEPT if FLEET company
--2004.3.5      :16/05/07 - Added FILTER in WHERE clause to EXCLUDE INTER-BRANCH SALES
--              :           to other Customer Group FRANCHISEES in the Bridgestone Retail
--              :           stable by inserting 'bsretail' in the Head_Office field
--              :           of the BRANCH in the Customer Catalog
--2004.3.7      :15/08/07 - Added leading and trailing quotes to Product/Manuf code
--2004.4.7      :18/09/09 - Added Merchant No in 'special_instr'  and replaced 'branch_name'
--              :           with Trading Name as per Denise van Gent new specs
--R.L	2015-03-12	:Added Inclusion List
-------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AC_Insert_CBilling_Temp]
    (
        @chkSalesCost tinyint,
        @chkExcludeInterBranch tinyint,
        @ExclusionsFilter varchar(8000),
        @InclusionFilter varchar(8000),
        @StartDayEndDate datetime,
        @EndDayEndDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql				varchar(8000),
            @RetCode			tinyint,
            @No_Days			int,
            @Temp_No_Days		Varchar(20)

    SET @RetCode = 0
    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
          
    Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
    
    --Select @StartDayEndDate

    SET @sql = ' INSERT AS_Transactions_CBilling_Temp '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + 'AS_Transactions_ID, '
    SET @sql = @sql + 'Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + 'cat_code, '
    SET @sql = @sql + 'drs_acc, '
    SET @sql = @sql + 'trs_ref, '
    SET @sql = @sql + 'trs_date, '
    SET @sql = @sql + 'qty, '
    SET @sql = @sql + 'amount, '
    SET @sql = @sql + 'gls_acc, '
    SET @sql = @sql + 'narr, '
    SET @sql = @sql + 'stock_group, '
    SET @sql = @sql + 'drs_apply, '
    SET @sql = @sql + 'sys_code, '
    SET @sql = @sql + 'updated, '
    SET @sql = @sql + 'interfaced, '
    SET @sql = @sql + 'drs_age_month, '
    SET @sql = @sql + 'stock_code, '
    SET @sql = @sql + 'area, '
    SET @sql = @sql + 'drs_alpha, '
    SET @sql = @sql + 'branch, '
    SET @sql = @sql + 'vat_amount, '
    SET @sql = @sql + 'cost_amount, '
    SET @sql = @sql + 'rep_comm, '
    SET @sql = @sql + 'process_type, '
    SET @sql = @sql + 'rep_code, '
    SET @sql = @sql + 'acct_type, '
    SET @sql = @sql + 'disc_amnt, '
    SET @sql = @sql + 'std_sell_price, '
    SET @sql = @sql + 'drs_trs_code, '
    SET @sql = @sql + 'trs_type, '
    SET @sql = @sql + 'acc_month, '
    SET @sql = @sql + 'acc_year, '
    SET @sql = @sql + 'con_acct_no, '
    SET @sql = @sql + 'zz_int01, '
    SET @sql = @sql + 'cntno, '
    SET @sql = @sql + 'line_disc1, '
    SET @sql = @sql + 'line_disc2, '
    SET @sql = @sql + 'stock_sell1, '
    SET @sql = @sql + 'no_of_deals, '
    SET @sql = @sql + 'zz_date01, '
    SET @sql = @sql + 'zz_date02, '
    SET @sql = @sql + 'zz_date03, '
    SET @sql = @sql + 'special_instr, '
    SET @sql = @sql + 'deals_flag, '
    SET @sql = @sql + 'deals_number, '
    SET @sql = @sql + 'vat_exempt_member, '
    SET @sql = @sql + 'cmonth, '
    SET @sql = @sql + 'cyear, '
    SET @sql = @sql + 'rep_call_status, '
    SET @sql = @sql + 'drsdiv_code, '
    SET @sql = @sql + 'crs_acc, '
    SET @sql = @sql + 'creation_date, '
    SET @sql = @sql + 'creation_time, '
    SET @sql = @sql + 'creation_userid, '
    SET @sql = @sql + 'creation_proc, '
    SET @sql = @sql + 'item_number, '
    SET @sql = @sql + 'rep_code2, '
    SET @sql = @sql + 'qty2, '
    SET @sql = @sql + 'deposit_amount, '
    SET @sql = @sql + 'job_number, '
    SET @sql = @sql + 'line_disc_amnt, '
    SET @sql = @sql + 'carhire_cntno, '
    SET @sql = @sql + 'currency, '
    SET @sql = @sql + 'exch_rate, '
    SET @sql = @sql + 'cyear_month, '
    SET @sql = @sql + 'zz_date04, '
    SET @sql = @sql + 'zz_date05, '
    SET @sql = @sql + 'zz_int02, '
    SET @sql = @sql + 'zz_int03, '
    SET @sql = @sql + 'zz_int04, '
    SET @sql = @sql + 'zz_int05, '
    SET @sql = @sql + 'zz_dec01, '
    SET @sql = @sql + 'zz_dec02, '
    SET @sql = @sql + 'zz_dec03, '
    SET @sql = @sql + 'zz_dec04, '
    SET @sql = @sql + 'zz_dec05, '
    SET @sql = @sql + 'zz_log01, '
    SET @sql = @sql + 'zz_log02, '
    SET @sql = @sql + 'zz_log03, '
    SET @sql = @sql + 'zz_log04, '
    SET @sql = @sql + 'zz_log05, '
    SET @sql = @sql + 'zz_log06, '
    SET @sql = @sql + 'zz_log07, '
    SET @sql = @sql + 'zz_char01, '
    SET @sql = @sql + 'zz_char02, '
    SET @sql = @sql + 'zz_char03, '
    SET @sql = @sql + 'zz_char04, '
    SET @sql = @sql + 'zz_char05, '
    SET @sql = @sql + 'key_glstrs, '
    SET @sql = @sql + 'key_history, '
    SET @sql = @sql + 'dumped, '
    SET @sql = @sql + 'company_name, '
    SET @sql = @sql + 'branch_name, '
    SET @sql = @sql + 'drs_name, '
    SET @sql = @sql + 'crs_name, '
    SET @sql = @sql + 'prd_grp_descr, '
    SET @sql = @sql + 'stk_descry, '
    SET @sql = @sql + 'status_ind, '
    SET @sql = @sql + 'customer_ref, '
    SET @sql = @sql + 'comments1, '
    SET @sql = @sql + 'comments2, '
    SET @sql = @sql + 'comments3, '
    SET @sql = @sql + 'comments4, '
    SET @sql = @sql + 'comments5, '
    SET @sql = @sql + 'comments6, '
    SET @sql = @sql + 'comments7, '
    SET @sql = @sql + 'comments8, '
    SET @sql = @sql + 'database_id, '
    SET @sql = @sql + 'system_id, '
    SET @sql = @sql + 'vat_reg_no, '
    SET @sql = @sql + 'email, '
    SET @sql = @sql + 'customer_cell_number, '
    SET @sql = @sql + 'customer_email_address, '
    SET @sql = @sql + 'Date_Captured, '
    SET @sql = @sql + 'User_ID, '
    SET @sql = @sql + 'AW_User_Companies_ID, '
    SET @sql = @sql + 'Slu_AW_Active_ID '
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' t.AS_Transactions_ID, '
    SET @sql = @sql + ' cb.Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + ' CASE WHEN t.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + ' THEN ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' WHEN t.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ''CR'' + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' END, '                                                        --cat_code
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --trs_ref
    SET @sql = @sql + ' t.Transaction_Date, '                                         --trs_date
    SET @sql = @sql + ' d.Quantity, '                                                 --qty
    SET @sql = @sql + ' ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), '     --amount,
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '      --narr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '     --stock_group
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --drs_apply
    SET @sql = @sql + ' ''"'' + ''SPI'' + ''"'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' 1, '                                                          --drs_age_month

--     SET @sql = @sql + ' CASE WHEN p.Manufacturer_Code IS NULL OR RTRIM(LTRIM(p.Manufacturer_Code)) = ''"'' + ''''   '
--     SET @sql = @sql + ' THEN p.Product_Code '
--     SET @sql = @sql + ' ELSE p.Manufacturer_Code '
--     SET @sql = @sql + ' END, '                                                        --stock_code
    SET @sql = @sql + ' CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(p.Product_Code, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ISNULL(p.Manufacturer_Code, '''') + ''"'' '
    SET @sql = @sql + ' END, '                                                        --stock_code

    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '            --drs_alpha
    SET @sql = @sql + ' ''"'' + ISNULL(uc.Network_Identity_Number, '''') + ''"'', '   --branch
    SET @sql = @sql + ' d.Tax_Amount, '                                               --vat_amount
    
    --> Product Cost Price data = 0
    IF @chkSalesCost = 0
    BEGIN
        SET @sql = @sql + ' 0, '
    END
    ELSE
    BEGIN    
        SET @sql = @sql + ' ROUND(ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0), 2), '    --cost_amount,
    END
    
    SET @sql = @sql + ' 0, '                                                         --rep_comm
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --process_type
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'','
    SET @sql = @sql + ' d.Discount_Amount, '                                         --disc_amnt
    SET @sql = @sql + ' d.Original_Price, '                                          --std_sell_price
    SET @sql = @sql + ' ''"'' + ''100'' + ''"'', '                                   --drs_trs_code
    SET @sql = @sql + ' 1, '                                                         --trs_type
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --acc_month,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --acc_year
    
    --     SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '           --on_acct_no
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(c.Customer_Number, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' 1, '                                                         --zz_int01
    SET @sql = @sql + ' 1, '                                                         --cntno
    SET @sql = @sql + ' CASE WHEN (d.Unit_Price * d.Quantity) <> 0 '
    
    --     SET @sql = @sql + ' THEN CONVERT(money, ABS(ROUND( (((d.Discount_Amount) / (d.Unit_Price * d.Quantity)) * 100), 2)) ) '
    SET @sql = @sql + ' THEN ABS(ROUND(CONVERT(money, ((d.Discount_Amount / (d.Unit_Price * d.Quantity)) * 100)), 2)) '
    
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END, '                                                       --line_disc1
    SET @sql = @sql + ' 0, '                                                         --line_disc2
    SET @sql = @sql + ' 0, '                                                         --stock_sell1
    SET @sql = @sql + ' 0, '                                                         --no_of_deals
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date01
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date02
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date03


--    SET @sql = @sql + ' ''"'' + ''"'', '                                             --special_instr
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Old_Customer_Number, ''''), 10) + ''"'', '        --special_instr


    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_flag
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_number
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --cmonth,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --cyear
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --drsdiv_code,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --crs_acc,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --creation_date,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_time,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_userid,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_proc,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --item_number,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code2,
    SET @sql = @sql + '  0 , '                                                       --qty2,
    SET @sql = @sql + '  0 , '                                                       --deposit_amount,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --job_number,
    SET @sql = @sql + '  0 , '                                                       --line_disc_amnt,
    SET @sql = @sql + '  0 , '                                                       --carhire_cntno,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --currency,
    SET @sql = @sql + '  0 , '                                                       --exch_rate,
    SET @sql = @sql + '  0 , '                                                       --cyear_month,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date04,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date05,
    SET @sql = @sql + '  0 , '                                                       --zz_int02,
    SET @sql = @sql + '  0 , '                                                       --zz_int03,
    SET @sql = @sql + '  0 , '                                                       --zz_int04,
    SET @sql = @sql + '  0 , '                                                       --zz_int05,
    SET @sql = @sql + '  0 , '                                                       --zz_dec01,
    SET @sql = @sql + '  0 , '                                                       --zz_dec02,
    SET @sql = @sql + '  0 , '                                                       --zz_dec03,
    SET @sql = @sql + '  0 , '                                                       --zz_dec04,
    SET @sql = @sql + '  0 , '                                                       --zz_dec05,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char01,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char02,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char03,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char04,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char05,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_glstrs,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_history,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --company_name


--    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --branch_name
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Trading_Name, ''''), 48) + ''"'', '             --branch_name

   
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --drs_name,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + ''"'', '                                                       --crs_name,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '              --prd_grp_descr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '               --stk_descry,
    SET @sql = @sql + ' ''"'' + ''NE'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Registration_No, ''''), 48) + ''"'', '          --customer_ref,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --comments1,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'', '          --comments2,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'', '           --comments3,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'', '             --comments4,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Authorization_No, ''''), 48) + ''"'', '         --comments5,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Odometer_Reading, ''''), 48) + ''"'', '         --comments6,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Engine_No, ''''), 48) + ''"'', '                --comments7,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Model_Year, '''') + ISNULL('' '' + cb.Make, '''') + ISNULL('' '' + cb.Model, ''''), 48) + ''"'', '          --comments8,
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Network_Identity_Number, ''''), 48) + ''"'', '  --system_id,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Tax_Number, ''''), 48) + ''"'', '                --vat_reg_no,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'', '                   --email,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Cell_No, ''''), 48) + ''"'', '                   --customer_cell_number,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'', '                --customer_email_address,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' t.Date_Captured, '
    SET @sql = @sql + ' t.User_ID, '
    SET @sql = @sql + ' t.AW_User_Companies_ID, '
    SET @sql = @sql + ' t.Slu_AW_Active_ID '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '    INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '    LEFT JOIN AS_Transactions_CBilling cb '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = cb.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 Lup_AP_Product_Types pt '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @sql = @sql + '    INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '    INNER JOIN AW_User_Companies uc '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = uc.AW_User_Companies_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 + '    INNER 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 + '    INNER 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 + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '

    IF @chkExcludeInterBranch = 1
        BEGIN
            SET @sql = @sql + '       ISNULL(LOWER(RTRIM(LTRIM(c.Head_Office))), '''') <> ''bsretail'' AND '
        END

    SET @sql = @sql + '      (t.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '       t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '       t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

-- Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
-- Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  

    SET @sql = @sql + 'ORDER BY t.AS_Transactions_ID '

IF LEN(@sql) >= 8000
    BEGIN
        SET @RetCode = 1

        RETURN @RetCode
    END

EXEC (@sql)
--Select @sql
SET @RetCode = 2

RETURN @RetCode
Go
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
-------------------------------------------------------------------------------
--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
--V6.2 RL	2015-06-09	:Removed inserting default print description
--						 From V6.0 If Print Description is blank, normal description is used
--V6.2	RL	2015-12-02	:Insert Default Bin location for new products
--V6.2	RL	2016-06-08	:Don't create a new product if a disabled product exists
-------------------------------------------------------------------------------

CREATE PROCEDURE [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

	Declare @ProductID int

	IF NOT EXISTS
	(
		SELECT 1
		FROM AP_Products
		WHERE Product_Code = @ProductCode
		AND Lup_AP_Product_Manufacturers_ID = @ManufacturerID
		AND Slu_AW_Active_ID <> 1
	)
	BEGIN
		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), From V6.0 If Print Description is blank, normal description is used
				@ProductCode,
				@ProductCode,
				@ManufacturerID,
				@ProductCode,
				LEFT(@ProductDesc, 50),
				1,
				1,
				1,
				1,
				@LastCost,
				0,
				@Price1EffectiveDate,
				@Price1,
				@Price2,
				@UserID
			)

		SELECT @ProductID = Scope_Identity()        
		
		--V6.2 Update Bin Qty
		INSERT INTO AP_Products_Bins
		(
			AP_Products_ID, 
			Lup_AP_Product_Bins_ID, 
			On_Hand, 
			Date_Captured, 
			[User_ID], 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID
		)
		Values
		(
			@ProductID,
			1,
			0,
			GETDATE(),
			@UserID,
			1,
			1							
		)
	END

SET NOCOUNT OFF
GO
EXECUTE sp_bindefault @defname = N'[dbo].[df_Nullstring]', @objname = N'[dbo].[AS_Transactions].[Customer_Reference]'
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Bin_History_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Bin_History_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Bin_History_Select
--Purpose       :Fetch a list of Bin Allocation Batchs
--Date          :2016/04/06
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Bin_History_Select]
    (
        @AP_Products_ID		INT,
        @FromDate			DATETIME,
        @ToDate				DATETIME       
    )
AS

SET NOCOUNT ON

	SELECT	h.Date_Captured,
			h.Movement_Source,
			ISNULL(u.FirstName,'') + ' ' + ISNULL(u.Surname,'') AS 'User',
			b.[Description],
			h.From_Bin_Previous_On_Hand As 'Previous Quantity',
			h.From_Bin_New_On_Hand As 'New Quantity',
			h.Batch_No
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins b
			ON h.From_Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID 
	WHERE h.AP_Products_ID = @AP_Products_ID
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	ORDER BY h.Date_Captured, h.From_Lup_AP_Product_Bins_ID

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Products_Bins_Hist_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Products_Bins_Hist_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Products_Bins_Hist_Insert
--Purpose       :maintain Product Bins
--Date          :2015-02-02
--Authors       :RL
--Mods          :
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Products_Bins_Hist_Insert]
    (
    	@ProductID					int,
        @From_Bin_ID				int,
        @From_Bin_Previous_On_Hand	decimal(9,3),
        @To_Bin_ID					int,
        @To_Bin_Previous_On_Hand	decimal(9,3),
    	@Qty						decimal(9,3), --From V6.2 This is the bin on hand qty
    	@Source						varchar(10),
    	@Batch_No					int,
    	@UserID						int,
    	@CompanyID					int
    )
AS

SET NOCOUNT ON

	Declare @Bin_Prev_On_Hand decimal(9,3),
            @On_Hand_Diff decimal(9,3),
            @New_On_Hand decimal(9,3),
            @AP_Products_Bins_History_ID int

    SET @On_Hand_Diff = 0
    SET @New_On_Hand = 0
    SET @Bin_Prev_On_Hand = 0
    SET @AP_Products_Bins_History_ID = 0
    --SET @Batch_No = 0

 	--> Calculate Product on hand diff
	--SELECT @Bin_Prev_On_Hand = On_Hand
	--FROM AP_Products_Bins
	--WHERE AP_Products_ID = @ProductID
	--AND Lup_AP_Product_Bins_ID = @ProductBinID
	
	SELECT @New_On_Hand = @Bin_Prev_On_Hand + @Qty
	
	IF @Qty <> 0
	BEGIN --@Qty <> 0
		--From Bin
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @From_Bin_ID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = On_Hand - @Qty
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @From_Bin_ID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@From_Bin_ID,
				@Qty,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		--To Bin
		IF EXISTS
		(
			SELECT 1
			FROM AP_Products_Bins
			WHERE AP_Products_ID = @ProductID
    		AND Lup_AP_Product_Bins_ID = @To_Bin_ID	
		)
		BEGIN
			UPDATE AP_Products_Bins
			SET On_Hand = On_Hand + @Qty
			WHERE AP_Products_ID = @ProductID
			AND Lup_AP_Product_Bins_ID = @To_Bin_ID
		END
		ELSE
		BEGIN
			INSERT INTO AP_Products_Bins
			(
				AP_Products_ID, 
				Lup_AP_Product_Bins_ID, 
				On_Hand, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID
			)
			VALUES
			(
				@ProductID,
				@To_Bin_ID,
				@Qty,
				GETDATE(),
				@UserID,
				@CompanyID,
				1
			)		
		END	

		IF @Source <> ''
		BEGIN		
			--SELECT @AP_Products_Bins_History_ID = MAX(AP_Products_Bins_History_ID)
			--FROM AP_Products_Bins_History
			--WHERE AP_Products_ID = @ProductID
			
			--SELECT @Batch_No = MAX(Batch_No)
			--FROM AP_Products_Bins_History
			
			--IF @Batch_No IS NULL
			--	SET @Batch_No = 0
				
			--SET @Batch_No = @Batch_No + 1
			
			--IF @AP_Products_Bins_History_ID = 0
			--BEGIN
				INSERT INTO AP_Products_Bins_History
				(
					Batch_No, 
					AP_Products_ID, 
					From_Lup_AP_Product_Bins_ID, 
					From_Bin_Previous_On_Hand, 
					From_Bin_New_On_Hand, 
					To_Lup_AP_Product_Bins_ID, 
					To_Bin_Previous_On_Hand, 
					To_Bin_New_On_Hand, 
					Movement_Source, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID		
				)
				VALUES
				(
					@Batch_No, 
					@ProductID, 
					@From_Bin_ID, 
					@From_Bin_Previous_On_Hand, 
					@From_Bin_Previous_On_Hand - @Qty, 
					@To_Bin_ID, --To_Lup_AP_Product_Bins_ID
					@To_Bin_Previous_On_Hand, --To_Bin_Previous_On_Hand
					@To_Bin_Previous_On_Hand + @Qty, --To_Bin_New_On_Hand
					@Source, 
					GETDATE(), 
					@UserID, 
					@CompanyID, 
					1 --Slu_AW_Active_ID
				)			
			--END
			--ELSE
			--BEGIN			
			--	INSERT INTO AP_Products_Bins_History
			--	(
			--		Batch_No, 
			--		AP_Products_ID, 
			--		From_Lup_AP_Product_Bins_ID, 
			--		From_Bin_Previous_On_Hand, 
			--		From_Bin_New_On_Hand, 
			--		To_Lup_AP_Product_Bins_ID, 
			--		To_Bin_Previous_On_Hand, 
			--		To_Bin_New_On_Hand, 
			--		Movement_Source, 
			--		Date_Captured, 
			--		[User_ID], 
			--		AW_User_Companies_ID, 
			--		Slu_AW_Active_ID		
			--	)
			--	SELECT
			--		@Batch_No, 
			--		@ProductID, 
			--		@ProductBinID, 
			--		@Bin_Prev_On_Hand, 
			--		@New_On_Hand, 
			--		To_Lup_AP_Product_Bins_ID, 
			--		To_Bin_New_On_Hand, 
			--		To_Bin_New_On_Hand, 
			--		@Source, 
			--		GETDATE(), 
			--		@UserID, 
			--		@CompanyID, 
			--		1
			--	FROM AP_Products_Bins_History
			--	WHERE AP_Products_Bins_History_ID = @AP_Products_Bins_History_ID		
			--END
		END
	END --@Qty <> 0
SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Inventory_Adjustments]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Inventory_Adjustments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Inventory_Adjustments
--Purpose       :Retrieves filtered list of Inventory Adjustments
--              :
--Parameters    :
--Date          :2002/02/13
--Authors       :TB
--Version       :1.0.0
--MODS          :24/04/02 - Reduced number of columns to improve printing
--              :27/04/02 - Replaced User Firstname, Surname with UserName
--              :16/10/02 - Added Start and End date filter when retieving ALL adj
--              :31/05/03 - Added NEW and PREVIOUS Average_Cost fields & Calcs
--              :08/01/04 - Fixed Search Filter sequence
--              :09/01/04 - Added filter by Adjustment Type with @AdjustType
--V6.2	RL		:2016-04-25 - Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Filter_Inventory_Adjustments]
    (
        @CompanyID int, 
        @AdjustType tinyint,
        @SearchFilter int,
        @Value int,
        @SearchDescription varchar(50),
        @StartDate as datetime,
        @EndDate as datetime
    )

AS

SET NOCOUNT ON


    IF @AdjustType = 0
        BEGIN
            --> ALL Adjustements
            IF @SearchFilter = 0
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> SUPPLIERS
            IF @SearchFilter = 1
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    JOIN AO_Suppliers s
                        ON p.Default_Supplier_ID = s.AO_Suppliers_ID
        		WHERE s.AO_Suppliers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> MANUFACTURER
            IF @SearchFilter = 2
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Manufacturers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> TYPES
            IF @SearchFilter = 3
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Types_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> GROUPS
            IF @SearchFilter = 4
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Groups_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> DEPARTMENTS
            IF @SearchFilter = 5
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Departments_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> LOCATIONS
            IF @SearchFilter = 6
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> PRODUCT DESCRIPTION SEARCH
            IF @SearchFilter = 7
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                     (p.[Description] LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%' OR
                      p.Product_Code LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%') AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

            ELSE
            --> LOCATIONS
            IF @SearchFilter = 10
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    LEFT OUTER JOIN AP_Products_Bins b
        		        ON p.AP_Products_ID = b.AP_Products_ID
        		    LEFT OUTER JOIN Lup_AP_Product_Bins pb
        				ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID    
        		WHERE pb.Lup_AP_Product_Bins_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

        END

    --> Adjustment Type Selected
    ELSE
        BEGIN
            --> ALL Adjustements
            IF @SearchFilter = 0
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> SUPPLIERS
            IF @SearchFilter = 1
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    JOIN AO_Suppliers s
                        ON p.Default_Supplier_ID = s.AO_Suppliers_ID
        		WHERE s.AO_Suppliers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> MANUFACTURER
            IF @SearchFilter = 2
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Manufacturers_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> TYPES
            IF @SearchFilter = 3
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Types_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> GROUPS
            IF @SearchFilter = 4
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Groups_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> DEPARTMENTS
            IF @SearchFilter = 5
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Departments_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> LOCATIONS
            IF @SearchFilter = 6
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC
        
            ELSE
            --> PRODUCT DESCRIPTION SEARCH
            IF @SearchFilter = 7
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
        		WHERE a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (p.[Description] LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%' OR
                      p.Product_Code LIKE '%' + rtrim(ltrim(@SearchDescription)) + '%') AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

            ELSE
            --> BINS
            IF @SearchFilter = 10
           		SELECT
                    a.AP_Inventory_Adjustments_ID AS [ID],
                    dbo.fn_AB_Get_Ending_GL_Period(month(a.Date_Captured), year(a.Date_Captured)) AS [Period],
                    a.AP_Products_ID AS [ProductID],
                    p.[Description] AS [Product],
                    p.Product_Code AS [Code],
                    t.[Description] AS [Type],
                    a.Note AS [Note],
                    a.Previous_On_Hand AS [Prev O/H],
                    a.New_On_Hand AS [New O/H],
                    a.Previous_Last_Cost AS [Prev Last Cost],
                    a.New_Last_Cost AS [New Last Cost],
                    a.Previous_Average_Cost AS [Prev Ave. Cost],
                    a.New_Average_Cost AS [New Ave. Cost],
                   (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],
                   (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],
        --             a.Previous_Job_Reserved AS [Prev Job Res],
        --             a.New_Job_Reserved AS [New Job Res],
        --             a.Previous_Sales_Order_Reserved  AS [Prev S/O Res],
        --             a.New_Sales_Order_Reserved  AS [New S/O Res],
        --             a.Previous_Quote_Reserved AS [Prev Quot Res],
        --             a.New_Quote_Reserved AS [New Quote Res],
                    a.Date_Captured AS [Date],
                    u.UserName AS [User]
        		FROM AP_Inventory_Adjustments a
                    LEFT JOIN AP_Products p 
        		        ON a.AP_Products_ID = p.AP_Products_ID
                    LEFT JOIN Sys_AP_Adjustment_Types t 
        		        ON a.Sys_AP_Adjustment_Types_ID = t.Sys_AP_Adjustment_Types_ID
                    LEFT JOIN AW_Users u
        		        ON a.[User_ID] = u.AW_Users_ID
                    LEFT OUTER JOIN AP_Products_Bins b
        		        ON p.AP_Products_ID = b.AP_Products_ID
        		    LEFT OUTER JOIN Lup_AP_Product_Bins pb
        				ON pb.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID            		        
        		WHERE p.Lup_AP_Product_Locations_ID = @Value AND
                      a.AW_User_Companies_ID = @CompanyID AND
                      a.Sys_AP_Adjustment_Types_ID = @AdjustType AND
                     (a.Date_Captured >= @StartDate AND
                      a.Date_Captured <= @EndDate)
        		ORDER BY a.Date_Captured DESC

        END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Product_Search_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Product_Search_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Product_Search_Lups
--Purpose       :Supplier & Product Lookups
--Functionality :
--Parameters    :	
--Date          :2002/01/20
--Authors       :TB
--Version       :1.0.0
--MODS          :23/09/02 - Inserted check if Slu_AW_Active_ID = 1 in @Option = 1
--              :           to SELECT ONLY Active Suppliers
--              :           This sp used in Purchase Orders & Stock Adjustments
--              :28/09/03 - Added Users in option 7
--              :01/10/03 - Added ALL Suppliers (not only ACTIVE ones) in option 8
--              :13/10/03 - Added Connection Manager (Remote Access) in option 9
--              :08/01/04 - Added Stock Adjustment Types in option 10
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Select_Product_Search_Lups]
    (
    	@Option int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    BEGIN

    	IF @Option = 1    --> Supplier
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID AND
                  Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name ASC
    	ELSE 
    	IF @Option = 2    --> Manufacturer
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			  [Description] AS [Manufacturer] 
    		FROM Lup_AP_Product_Manufacturers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 3    --> Type
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			  [Description] AS [Type] 
    		FROM Lup_AP_Product_Types
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 4    --> Group
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			  [Description] AS [Group] 
    		FROM Lup_AP_Product_Groups	
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 5    --> Department
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			  [Description] AS [Department] 
    		FROM Lup_AP_Product_Departments
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 6    --> Location
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			  [Description] AS [Location] 
    		FROM Lup_AP_Product_Locations
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description]
    	ELSE 
    	IF @Option = 7    --> Users
          	SELECT AW_Users_ID as [ID],
--                   ISNULL(Surname, '') + ISNULL(', ' + FirstName, '') AS [User]
                   ISNULL(FirstName + ' ', '') + ISNULL(Surname, '') AS [User]
            FROM AW_Users 
            ORDER BY [User]
        ELSE
    	IF @Option = 8    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			   Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY Supplier_Name ASC
        ELSE
    	IF @Option = 9    --> Connection Manager (Remote Access)
    		SELECT AW_Remote_Access_ID AS [ID],
    			   NodeName AS [Originator] 
    		FROM AW_Remote_Access
    		WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY NodeName ASC
        ELSE
    	IF @Option = 10    --> Stock Adjustment Types
    		SELECT Sys_AP_Adjustment_Types_ID AS [ID],
    			   [Description] AS [Type] 
    		FROM Sys_AP_Adjustment_Types
        ELSE
    	IF @Option = 11    --> Product Bins
    		SELECT Lup_AP_Product_Bins_ID AS [ID],
    			   [Description] AS [Bin] 
    		FROM Lup_AP_Product_Bins


    END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Bin_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Bin_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Product_Bin_Select
--Purpose       :Returns details for a specific product and bin
--Functionality :
--Parameters    :	
--Date          :2016/04/28
--Authors       :RL
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Bin_Select]
    (
    	@AP_Products_ID int,
    	@BinID			int,
    	@CompanyID		int
    )

AS

SET NOCOUNT ON
		SELECT  l.Lup_AP_Product_Bins_ID,
				l.[Description],
				ISNULL(l.Email,'') As [Email],
				b.On_Hand
		FROM Lup_AP_Product_Bins l
			Inner Join AP_Products_Bins b
				On l.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
		WHERE b.AP_Products_ID = @AP_Products_ID
		AND	b.Lup_AP_Product_Bins_ID = @BinID

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

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

AS

SET NOCOUNT ON

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


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


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

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

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

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

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

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


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


    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Drop_Enterprise_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Management_Accounts
--Purpose       :Drops and re-creates AB_Enterprise_Management_Accounts table
--Date          :2015-08-20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Management_Accounts]
AS

    DECLARE @ReturnValue int
    SET @ReturnValue = 0

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Management_Accounts]
        
        CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
        	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[IS1ID] [int] NULL ,
        	[IS2ID] [int] NULL ,        	
        	[IS3ID] [int] NULL ,        	
        	[IS4ID] [int] NULL ,
        	[GLID] [int] NULL ,
        	[DivisionID] [int] NULL ,
        	[GroupID] [int] NULL ,
        	
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	
        	[GLDivision] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[GLGroup] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[AccountNo] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[Account] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	
        	[TotalActual] [money] NULL,
        	[TotalBudget] [money] NULL,
        	[TotalYTDActual] [money] NULL,
        	[TotalYTDBudget] [money] NULL        	
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Management_Accounts_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Bins_Switch]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Bins_Switch]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AP_Bins_Switch
--Purpose       :Switch Product Bins on or off.
--				 If Products Bins are switched off, then move all products to the default Bins
--Date          :2016-05-02
--Version		:V6.2
--Authors       :RL
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AP_Product_Bins_Switch]
    (
    	@Switch					int,	--0	OFF, 1 ON
    	@UserID					int,
		@CompanyID				int
    )

AS

SET NOCOUNT ON

    DECLARE @From_Qty						decimal(9,3),
			@From_AP_Products_Bins_ID		int,
			@From_Lup_AP_Product_Bins_ID	int,
			
			@To_Lup_AP_Product_Bins_ID		int,			
			@To_Bin_Previous_On_Hand		decimal(9,3),
			@To_AP_Products_Bins_ID			int,
			
			@Previous_Bin_Switch			int,
			@AP_Products_ID					int
			
			
	SET @Previous_Bin_Switch = 1
		
	SELECT @Previous_Bin_Switch = Control_Value
	FROM Sys_AW_Options
	Where Control_Name = 'chkEnableProductBins'
	AND Control_Index = 0

	IF ( (@Previous_Bin_Switch = 1) AND (@Switch = 0) )
	BEGIN
		
		DECLARE GetData CURSOR
		FOR
		SELECT  AP_Products_Bins_ID,
				AP_Products_ID,
				Lup_AP_Product_Bins_ID,
				On_Hand
		FROM AP_Products_Bins
		WHERE Lup_AP_Product_Bins_ID <> 1
		AND On_Hand <> 0
		
		OPEN GetData
		FETCH NEXT FROM GetData INTO @From_AP_Products_Bins_ID, @AP_Products_ID, @From_Lup_AP_Product_Bins_ID, @From_Qty
		WHILE @@FETCH_STATUS = 0
		BEGIN

			SET @To_Bin_Previous_On_Hand = 0
			SET @To_AP_Products_Bins_ID = 0
			SET @To_Lup_AP_Product_Bins_ID = 1

			IF EXISTS
			(
				SELECT 1
				FROM AP_Products_Bins
				WHERE AP_Products_ID = @AP_Products_ID
    			AND Lup_AP_Product_Bins_ID = 1	
			)
			BEGIN
				SELECT	@To_Bin_Previous_On_Hand = On_Hand,
						@To_AP_Products_Bins_ID = AP_Products_Bins_ID
				FROM AP_Products_Bins
				WHERE AP_Products_ID = @AP_Products_ID
    			AND Lup_AP_Product_Bins_ID = 1	
			
				--From Bin
				UPDATE AP_Products_Bins
				SET On_Hand = 0
				WHERE AP_Products_Bins_ID = @From_AP_Products_Bins_ID
				
				--To Bin
				UPDATE AP_Products_Bins
				SET On_Hand = On_Hand + @From_Qty
				WHERE AP_Products_Bins_ID = @To_AP_Products_Bins_ID			
			END
			ELSE
			BEGIN
				INSERT INTO AP_Products_Bins
				(
					AP_Products_ID, 
					Lup_AP_Product_Bins_ID, 
					On_Hand, 
					Date_Captured, 
					[User_ID], 
					AW_User_Companies_ID, 
					Slu_AW_Active_ID
				)
				VALUES
				(
					@AP_Products_ID,
					1,
					@From_Qty,
					GETDATE(),
					@UserID,
					@CompanyID,
					1
				)	
				
				--From Bin
				UPDATE AP_Products_Bins
				SET On_Hand = 0
				WHERE AP_Products_Bins_ID = @From_AP_Products_Bins_ID
				
				--To Bin
				SET @To_Bin_Previous_On_Hand = 0
			END				
			
			INSERT INTO AP_Products_Bins_History
			(
				Batch_No, 
				AP_Products_ID, 
				From_Lup_AP_Product_Bins_ID, 
				From_Bin_Previous_On_Hand, 
				From_Bin_New_On_Hand, 
				To_Lup_AP_Product_Bins_ID, 
				To_Bin_Previous_On_Hand, 
				To_Bin_New_On_Hand, 
				Movement_Source, 
				Date_Captured, 
				[User_ID], 
				AW_User_Companies_ID, 
				Slu_AW_Active_ID		
			)
			VALUES
			(
				'0',									--Batch_No, 
				@AP_Products_ID, 
				@From_Lup_AP_Product_Bins_ID, 
				@From_Qty,								--From_Bin_Previous_On_Hand
				0,										--From_Bin_New_On_Hand
				
				1,										--To_Lup_AP_Product_Bins_ID
				@To_Bin_Previous_On_Hand,				--To_Bin_Previous_On_Hand
				@To_Bin_Previous_On_Hand + @From_Qty,	--To_Bin_New_On_Hand
				
				'SYS Option',							--Movement_Source
				GETDATE(), 
				@UserID, 
				@CompanyID, 
				1
			)			
			
			FETCH NEXT FROM GetData INTO @From_AP_Products_Bins_ID, @AP_Products_ID, @From_Lup_AP_Product_Bins_ID, @From_Qty	
		END
		CLOSE GetData
		DEALLOCATE GetData
	END

SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[sp_AW_Select_User_Lups]    Script Date: 07/15/2013 03:22:47 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_User_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_User_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Lups
--Purpose       :User Catalog Lups
--Functionality : 
--Parameters    : 
--Date          :2001/11/17
--Authors       :TB
--MODS          :27/09/02 - Added ORDER BY Description for Applications LUP
--              :           and reversed User FirstName, Surname order
--              :02/10/02 - Added IsCashier & IsSupervisor as Choice 5 & 6
--              :25/07/03 - Option 3: Select ONLY ACTIVE Applications
--              :03/01/04 - Added IsDBAdmin, IsCRM, IsController, Delivery Methods
--              :           as Choice 7, 8, 9 & 10 for Credit Manager
--              :22/09/05 - Added IsAccountant as Choice 11
--2004.3.7      :12/09/07 - Added IsDataExporter as Choice 12
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor as Choice 13
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController as Choice 14
--2015.6.2 RGL  :2015-11-12 - Added Product Bins as Choice 16
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_User_Lups]
    (
    	@Choice int
    )
AS

SET NOCOUNT ON

    BEGIN 
    	--> Active
    	IF @Choice = 1 
    		SELECT Slu_AW_Active_ID AS [ID], 
    			[Description] AS [Active] 
    		FROM Slu_AW_Active
    
    	--> User Companies
    	ELSE
    	IF @Choice = 2
    		SELECT AW_User_Companies_ID AS [ID], 
    			Company_Name AS [Company] 
    		FROM AW_User_Companies
    
    	--> Applications
    	ELSE 
    	IF @Choice = 3
    		SELECT Sys_AW_Applications_ID AS [ID],
    			[Description] AS [Applications]
    		FROM Sys_AW_Applications
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    	--> Users
    	ELSE 
    	IF @Choice = 4
    		SELECT AW_Users_ID AS [ID],
    			    ISNULL(Surname, '') + ISNULL(' ' + FirstName, '') AS [User]
    		FROM AW_Users 
    		WHERE AW_Users_ID <> -1
    		ORDER BY Surname, FirstName
    
    	--> IsCashiers
    	ELSE 
    	IF @Choice = 5
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [Cashier]
    		FROM Slu_AW_YesNo 
    
    	--> IsSupervisor
    	ELSE 
    	IF @Choice = 6
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Supervisor]
    		FROM Slu_AW_YesNo 

    	--> IsDBAdmin
    	ELSE 
    	IF @Choice = 7
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [DBAdmin]
    		FROM Slu_AW_YesNo 
    
    	--> IsCRM
    	ELSE 
    	IF @Choice = 8
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [CRM]
    		FROM Slu_AW_YesNo 
    
    	--> IsCreditController
    	ELSE 
    	IF @Choice = 9
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Controller]
    		FROM Slu_AW_YesNo 

        --> Delivery Methods
        ELSE
        IF @Choice = 10
          	SELECT Sys_AW_Delivery_Methods_ID as [ID],
                   ISNULL(Description, '') AS [Description]
            FROM Sys_AW_Delivery_Methods 

        --> IsAccountant
        ELSE
        IF @Choice = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Accountant]
    		FROM Slu_AW_YesNo 

        --> IsDataExporter
        ELSE
        IF @Choice = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [DataExport]
    		FROM Slu_AW_YesNo 

        --> IsProcurementSupervisor
        ELSE
        IF @Choice = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [ProcureSuper]
    		FROM Slu_AW_YesNo
    		 
		--> IsLevyController
        ELSE
        IF @Choice = 14
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [LevyCont]
    		FROM Slu_AW_YesNo     		
		--> IsRecordManager
        ELSE
        IF @Choice = 15
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [RecordsManager]
    		FROM Slu_AW_YesNo     		

        ELSE
        IF @Choice = 16
    		SELECT Lup_AP_Product_Bins_ID AS [ID],
    			   ISNULL([Description], '') AS [ProductBins]
    		FROM Lup_AP_Product_Bins     		
        ELSE
        --> IsBinSuper
        IF @Choice = 17
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [BinSuper]
    		FROM Slu_AW_YesNo     		

    END

SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[sp_AW_Select_User_Catalog]    Script Date: 07/15/2013 12:35:57 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_User_Catalog]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_User_Catalog]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Catalog
--Date          :2001/11/17
--Authors       :TB
--MODS          :02/10/02 - Added IsCashier & IsSupervisor
--              :20/12/03 - Added IsDBAdmin
--              :03/01/03 - Added IsAdministrator, IsController
--              :22/09/05 - Added IsAccountant
--2004.3.7      :12/09/07 - Added IsDataExporter
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController
--2004.5.9 RGL  :2013-07-15 - Added IsRecordsManager
--2015.6.2 RGL  :2015-11-12 - Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Select_User_Catalog]
    (
    	@User_ID int    )

AS

SET NOCOUNT ON

    SELECT AW_Users_ID AS [ID], 
    	Surname AS [Surname], 
    	FirstName AS [First Name], 
    	UserName AS [User Name], 
    	[Password] AS [Password], 
    	User_Home_Tel_Number AS [Home Tel No], 
        User_Cell_Number AS [Cell No], 
    	User_Email AS [E-mail Address], 
    	Activation_Date AS [Activation Date], 
    	Deactivation_Date AS [Deactivation Date], 
    	Unsuccessful_Logins AS [Unsuccessful Logins], 
    	Sys_AW_Applications_ID AS [Applications],
        Slu_AW_Active_ID AS [Active],
        IsCashier AS [IsCashier],
        IsSupervisor AS [IsSupervisor],
        IsDBAdmin AS [IsDBAdmin],
        IsCRM AS [IsCRM],
        IsController AS [IsController],
        Sys_AW_Delivery_Methods_ID AS [Delivery Method],
        IsAccountant AS [IsAccountant],
        IsDataExporter AS [IsDataExporter],
        IsProcurementSupervisor AS [IsProcureSuper],
        IsLevyController AS [IsLevyCont],
        IsRecordsManager AS [IsRecordsManager],
        Lup_AP_Product_Bins_ID AS [ProductBins],
        IsBinSuper AS [IsBinSuper]
    FROM AW_Users 
    WHERE AW_Users_ID = @User_ID

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

-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Product_Bin_Status
--Purpose       :Select if User = Product Bin Supervisor
--Functionality :User MUST BE IsBinSuper to authorise
--Date          :2016-05-02
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AW_Check_Product_Bin_Status]
	(
        @Password varchar(20),
		@BinSuperID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @BinSuperID = 0

	SELECT TOP 1 @BinSuperID = AW_Users_ID
	FROM AW_Users
    WHERE IsBinSuper = 1 AND
          Slu_AW_Active_ID = 1 AND
          [Password] = @Password

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Bins_Multi_CHK]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Bins_Multi_CHK]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :144 sp_AP_Product_Bins_Multi_CHK
--Purpose       :Checks if products exist in other bins
--Date          :2016-05-09
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Product_Bins_Multi_CHK]
    (
    	@ProductID				int,
        @ProductBinID			int,
    	@CompanyID				int,
    	@OtherBinQty			decimal(9,3) OUTPUT,
    	@ConsignmentStockQty	decimal(9,3) OUTPUT
    )

AS

SET NOCOUNT ON

	SELECT @ConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@ProductID)
	
	SELECT @OtherBinQty = ISNULL(SUM(On_Hand),0)
	FROM AP_Products_Bins
	WHERE AP_Products_ID = @ProductID
	AND AW_User_Companies_ID = @CompanyID
	AND Lup_AP_Product_Bins_ID <> @ProductBinID
    
    SELECT @OtherBinQty, @ConsignmentStockQty
    
SET NOCOUNT OFF
GO
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 [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,
            @ProductBinID	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),
                       ISNULL(Lup_AP_Product_Bins_ID,1)
                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,
                @ProductBinID

        	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

				--Update Bin Qty
				IF @Variance <> 0
				BEGIN
					EXEC sp_AP_Products_Bins_Update_Insert 
						@ProductID,		--@ProductID int,
						@ProductBinID,	--@ProductBinID int,
    					@Variance,		--@Qty decimal(9,3)
    					'STOCK TAKE',	--@Source varchar(10),
    					0,				--@Batch_No
    					@UserID,		--@UserID int,
    					@CompanyID		--@CompanyID int
				END	

                ------------------------------------------------------------
                --> 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,
            			Lup_AP_Product_Bins_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,
            			@ProductBinID
                    )
                ------------------------------------------------------------

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

        	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
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AO_GRV_Select_Outstanding_Order_Details
--Purpose       :Fetches Outstanding Order items for an outstanding order
--              :
--Date			:2002/01/13
--Authors		:TB
--MODS          :
--2004.3.5      :29/04/07 - Added Product_Code field and [User] and [Active] JOINS
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_GRV_Select_Outstanding_Order_Details]
    (
    	@Orders_ID int
    )

AS

SET NOCOUNT ON

	SELECT OD.AO_Order_Details_ID AS [ID],
        OD.AO_Orders_ID AS [FK ID],
        OD.AP_Products_ID AS [Products ID],
        P.[Description] AS [Product],
        P.Product_Code AS [Code],
        OD.Order_Qty AS [Qty],	
        OD.Free_Qty AS [Free Qty],
        OD.Back_Order_Qty AS [B/O Qty],
        OD.Received_Qty AS [Received Qty],
        OD.Receipt_Date AS [Receipt Date],	
        OD.Unit_Price AS [Unit Price],
        
        OD.Trade_Discount_Formula_ID AS [Trade_Discount_Formula_ID],
        OD.Trade_Discount_Amount AS [Trade Disc],
        OD.Trade_Discount_Percentage AS [Trade Disc Perc],
        OD.Rebate_Formula_ID AS [Rebate_Formula_ID],
        OD.Rebate_Discount_Amount AS [Rebate Disc],
        OD.Rebate_Discount_Percentage AS [Rebate Disc Perc],
        OD.Other_Discount_Formula_ID AS [Other_Discount_Formula_ID],
        OD.Other_Discount_Amount AS [Other Disc],
        OD.Other_Discount_Percentage AS [Other Disc Perc],
        
        OD.Net_Amount AS [Net Amount],
        OD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        TC.[Description] AS [Tax Code],
        OD.Tax_Amount AS [Tax],
        OD.Total_Cost AS [Total Cost],
        OD.Lead_Time AS [Lead Time],	
        OD.Date_Captured AS [Date Captured],
        OD.[User_ID] AS [User ID],
        u.UserName AS [User],
        OD.AW_User_Companies_ID AS [Company],
--        OD.Slu_AW_Active_ID AS [Active]
        a.[Description] AS [Active],
        P.On_Hand AS [On Hand]
    FROM AO_Order_Details OD
        LEFT JOIN AP_Products P
            ON OD.AP_Products_ID  = P.AP_Products_ID 
        LEFT JOIN Sys_AW_Tax_Codes TC
            ON OD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
        LEFT JOIN AW_Users u
            ON OD.[User_ID]  = u.AW_Users_ID
        LEFT JOIN Slu_AW_Active a
            ON OD.Slu_AW_Active_ID = a.Slu_AW_Active_ID

    WHERE OD.AO_Orders_ID = @Orders_ID AND
         (OD.Order_Qty + OD.Back_Order_Qty) > OD.Received_Qty


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

--------------------------------------------------------------------------------
--Description   :sp_AP_Post_Stock_Take_Adjustments_CHK
--Purpose       :Checks if stock take will push stock on hand into a negative
--				:if consignment stock exists against that product
--Date          :2016/05/10
--Authors       :RL
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Post_Stock_Take_Adjustments_CHK]
    (    
    	@StockTakeProcedureID	int,
    	@Message				Varchar(5000) OUTPUT
    )

AS

SET NOCOUNT ON

    DECLARE @StockTakeICHK Table

    (
		ProductID	int,
		OnHand		decimal(9,3),
		Variance	decimal(9,3),
		Consignment decimal(9,3)
     )
     
     DECLARE @Temp			Varchar(100),
			 @TotalVariance	decimal(9,3)

	SET @Message = ''

	INSERT INTO @StockTakeICHK(ProductID)
	SELECT DISTINCT AP_Products_ID
	FROM AP_Products_Stock_Takes
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID AND
    ISNULL(Variance, 0) <> 0 
    
--Select * From @StockTakeICHK

	UPDATE @StockTakeICHK
	SET OnHand = p.On_Hand
	FROM @StockTakeICHK t
		INNER JOIN AP_Products p
			ON t.ProductID = p.AP_Products_ID
			
--Select * From @StockTakeICHK	

	UPDATE @StockTakeICHK
	SET Consignment = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(ProductID),0)	
	
--Select * From @StockTakeICHK

	--SELECT ProductID, SUM(ISNULL(Variance, 0)) AS [TotalVariance]
	--FROM @StockTakeICHK
	--GROUP BY ProductID

	UPDATE @StockTakeICHK
	SET Variance = t.TotalVariance
	FROM @StockTakeICHK s
		INNER JOIN (SELECT AP_Products_ID, SUM(ISNULL(Variance, 0)) AS [TotalVariance]
					FROM AP_Products_Stock_Takes
					WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID
					AND ISNULL(Variance, 0) <> 0 
					GROUP BY AP_Products_ID) t
			ON s.ProductID = t.AP_Products_ID
			
--Select * From @StockTakeICHK

	--UPDATE @StockTakeICHK
	--SET Variance = SELECT SUM(ISNULL(p.Variance, 0)) FROM 
	--FROM @StockTakeICHK t
	--	INNER JOIN AP_Products_Stock_Takes p
	--		ON t.ProductID = p.AP_Products_ID

	IF EXISTS
	(
		SELECT 1
		FROM @StockTakeICHK
		WHERE Consignment > 0
		AND (OnHand + Variance) < Consignment
	)
	BEGIN
		
		DECLARE GetData CURSOR
		FOR
		SELECT ISNULL(p.Product_Code,'') + ' - ' + ISNULL(Description,'')
		FROM AP_Products p
			INNER JOIN @StockTakeICHK t
				ON p.AP_Products_ID = t.ProductID
		WHERE t.Consignment > 0
		AND (t.OnHand + t.Variance) < t.Consignment
		
		OPEN GetData
		
		FETCH NEXT FROM GetData INTO @Temp
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @Message = ''
				SET @Message = @Temp
			Else
				SET @Message = @Message + '
' + @Temp
		
			FETCH NEXT FROM GetData INTO @Temp
		END	
		CLOSE GetData
		DEALLOCATE GetData
	END

	SELECT @Message AS [Message]

GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_Stock_Take_Variance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_Stock_Take_Variance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Stock_Take_Variance
--Purpose       :
--Date          :2009/02/19
--Authors       :TB
--MODS          :
----V6.3	RL	2017-02-01	:Changed On_Hand_Calc Back to On_Hand - Original Inventory Value
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Stock_Take_Variance]
	(
        @StockTakeProcedureID int,
        @StockTotal money OUTPUT,
        @Variance money OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


    SELECT @StockTotal = SUM(ISNULL(On_Hand, 0) * ISNULL(Unit_Cost, 0)),
           @Variance = SUM(ISNULL(Variance_Calc, 0) * ISNULL(Unit_Cost, 0))
    FROM AP_Products_Stock_Takes
    WHERE AP_Stock_Take_Procedures_ID = @StockTakeProcedureID


    SET @ReturnValue = 1


RETURN @ReturnValue
GO
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
-------------------------------------------------------------------------------
--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 [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),
            @Oppisite_Qty decimal(9,3)


    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
            
            			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'Sale',			--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END				
		END

	ELSE
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty,
            [User_ID] = @UserID
            WHERE AP_Products_ID = @ProductID
            
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
    				@Oppisite_Qty,	--@Qty decimal(9,3)
    				'Sale',			--@Source varchar(10),
    				0,				--@Batch_No
    				@UserID,		--@UserID int,
    				@CompanyID		--@CompanyID int		    	
			END	            
		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()
	
	--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	--RL Check Rounding of Tax amount in code
	--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	Update AS_Transactions
	Set Total_Tax_Amount = (Select Sum(ISNULL(Tax_Amount,0)) From AS_Transaction_Details Where AS_Transactions_ID = @DocumentID),
		Total_Amount = (Select Sum(ISNULL(Extended_Amount,0)) From AS_Transaction_Details Where AS_Transactions_ID = @DocumentID) --Sum(ISNULL(Extended_Amount,0))
		--Date_Captured = '2016-01-01'
	Where AS_Transactions_ID = @DocumentID

RETURN @DocumentDetailsID
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[Lup_AP_Product_Bins]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN

	CREATE TABLE [Lup_AP_Product_Bins]
	(
		[Lup_AP_Product_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[Description] [varchar](50) NULL,
		[Email] [varchar](100) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		CONSTRAINT [PK_Lup_AP_Product_Bins] PRIMARY KEY CLUSTERED 
		(
			[Lup_AP_Product_Bins_ID] ASC
		)
	)
END
GO

	EXECUTE sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[Lup_AP_Product_Bins].[Date_Captured]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_ID]', @objname = N'[dbo].[Lup_AP_Product_Bins].[User_ID]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_Companies]', @objname = N'[dbo].[Lup_AP_Product_Bins].[AW_User_Companies_ID]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Active]', @objname = N'[dbo].[Lup_AP_Product_Bins].[Slu_AW_Active_ID]'
	GO

If NOT EXISTS
(
	SELECT 1
	FROM Lup_AP_Product_Bins
	WHERE Lup_AP_Product_Bins_ID = 1
)
BEGIN
	
	SET IDENTITY_INSERT [Lup_AP_Product_Bins] On

	INSERT INTO Lup_AP_Product_Bins
	(
		[Lup_AP_Product_Bins_ID],
		[Description],
		[Email]
	)
	VALUES
	(
		1,
		'<None>',
		''
	)
	
	SET IDENTITY_INSERT [Lup_AP_Product_Bins] Off
END
GO

If NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Lookup_Editor
	WHERE TableName = 'Lup_AP_Product_Bins'
)
BEGIN
	
	Declare @Sys_AW_Lookup_Editor_ID Int

	Set @Sys_AW_Lookup_Editor_ID = 0

	Select @Sys_AW_Lookup_Editor_ID = MAX(Sys_AW_Lookup_Editor_ID)
	From Sys_AW_Lookup_Editor

	Set @Sys_AW_Lookup_Editor_ID = @Sys_AW_Lookup_Editor_ID + 1
  	
	INSERT INTO Sys_AW_Lookup_Editor
	(
		Sys_AW_Lookup_Editor_ID,
		TableName,
		Caption,
		ColumnWidths,
		Slu_AW_Active_ID
	)
	VALUES
	(
		@Sys_AW_Lookup_Editor_ID,
		'Lup_AP_Product_Bins',
		'Product Bins',
		'0,1000,8000,0,0,0,1005',
		1
	)

END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Insert_GRN_Refund_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Insert_GRN_Refund_Detail]
GO
--------------------------------------------------------------------------------
--Description   :sp_AF_Insert_GRN_Refund_Detail
--Purpose       :Inserts GRN Factory Refund Details
--              :Lifted from sp_AO_Insert_GRV_Return
--Date          :2011/06/28
--Authors       :TB
--MODS          :
--V6.2	RL		:2016-06-22	:Product Bin qty changes
--V6.2	RL		:2016-06-22	:Added cost adjustment to AP_Inventory_Adjustments
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Insert_GRN_Refund_Detail]
    (		
    	@GRVID int,
    	@ProductID int,
    	@Qty decimal(9,3),
    	@FactoryCredit 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(9,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_Last_Cost money,
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @GRNValue money,
            @User_Name varchar(40),
            @ProductRef varchar(30),
            @ProdCode varchar(20),
            @AdjustmentType int,
            @Note varchar(70)

    BEGIN
        ---------------------------------------------------------------------------
        --> Get the CLAIM Product stuff
        ---------------------------------------------------------------------------
    	SELECT @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
               @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @ProdCode = ISNULL(Product_Code, '')
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID

        ---------------------------------------------------------------------------
        --> Calculate AVERAGE COST (lifted from Stock Returns)
        ---------------------------------------------------------------------------
        SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
        SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

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

        SET @New_On_Hand = @Prev_On_Hand - @Qty
        SET @New_Last_Cost = @FactoryCredit

        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
            (
                @GRVID,
                @ProductID,
                @Qty,
                @FactoryCredit,
                @TradeDisc,
                @RebateDisc,
                @OtherDisc,
                @NetAmount,
                @Tax_Code_ID,
                @TaxAmount,
                @TotalCost,
                @UserID,
                @CompanyID
            )


    	UPDATE AP_Products 
    	SET Last_Cost = ABS(@New_Last_Cost),
            Average_Cost = ABS(@New_Average_Cost),
            On_Hand = @New_On_Hand,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID
   
		EXEC sp_AP_Products_Bins_Update_Insert
 				@ProductID,		--@ProductID int,
				1,	--@ProductBinID int,
				@Qty,			--@Qty decimal(9,3)
				'FAC GRN',	--@Source varchar(10),
				0,				--@Batch_No
				@UserID,		--@UserID int,
				@CompanyID		--@CompanyID int  
								
    	--RL V6.2
        IF @Prev_Last_Cost <> @New_Last_Cost
		BEGIN

            --> Assign the Adjustment Type
            SET @AdjustmentType = 30    --Factory Returned

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

            SET @Note = 'Factory Claim by '

			SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'
			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_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			0 ,
        			0,
        			0,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID
                )

        END
    	
    END
GO
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
--V6.2	RL	2015-12-01	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [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),
            @Oppisite_Qty decimal(9,3)


    SET @DocumentDetailsID = 0


--     ---------------------------------------------------------------------------
--     --> Set Product Cost (The same Factory Credit that went into Inventory)
--     ---------------------------------------------------------------------------
--     SET @Cost = ROUND(@UnitCost, 2)
--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
--    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,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @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,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @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,
					--RL 2016-05-30 Original Price was always NULL. Original Unit Price = NUll, because it was assigned Unit Cost which was also NULL
                   @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
                        
			IF @Qty <> 0
			BEGIN
				SELECT @Oppisite_Qty = @Qty * -1
			
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,		--@ProductID int,
					1,	--@ProductBinID int,
					@Oppisite_Qty,			--@Qty decimal(9,3)
					'FAC CLREF',	--@Source varchar(10),
					0,				--@Batch_No
					@UserID,		--@UserID int,
					@CompanyID		--@CompanyID int
			END	    	
            
		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,
			--RL 2016-05-30 Unit_Cost is always positive
			@Cost,				--Unit_Cost
			-@UnitPrice,		--Unit_Price
			@OriginalPrice,		--Original_Price
			@Tax,
			@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

RETURN @DocumentDetailsID
GO
Update AS_Transaction_Details
Set AS_Transaction_Details.Unit_Cost = Unit_Cost * -1
From AS_Transactions t
	Inner Join AS_Transaction_Details d
		On t.AS_Transactions_ID = d.AS_Transactions_ID
Where ISNULL(d.Unit_Cost,0) < 0
And ISNULL(d.AS_Job_References_ID,0) > 0
And t.Sys_AW_Transaction_Types_ID = 4
GO

IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]
GO
-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers
--Purpose       :Retrieves Ageing Totals of All Suppliers
--Date          :2001/08/26
--Authors       :TB
--MODS          :
--2004.5.2      :11/07/11 - Fixed Supplier_Name field length to new size 40 !!!!
-------------------------------------------------------------------------------

CREATE FUNCTION [fn_AO_Supplier_Ageing_Non_Grouped_All_Suppliers]
    (    	 
		@D0 DateTime, 
    	@D1 DateTime,
    	@D2 DateTime,
    	@D3 DateTime,
    	@D4 DateTime,
    	@D5 DateTime,
    	@D6 DateTime,
    	@D7 DateTime,
		@CompanyID int
    )

RETURNS @AgeTable TABLE 
	(
        [ID] int,
        [SupplierID] int, 
        [Supplier_Name] varchar(40),
        [Date] datetime,
        [Payment] money,
        [Amount] money,
        [Current] money,
        [30 Days] money,
        [60 Days] money,
        [90 Days] money,
        [120 Days] money, 
        [150 Days] money,
        [180+ Days] money
    )

AS

BEGIN

	INSERT @AgeTable
	SELECT
            t.AO_Transactions_ID AS [ID], 
            t.AO_Suppliers_ID AS [SupplierID],  
            s.Supplier_Name AS [Supplier_Name],
            t.Date_Captured AS [Transaction_Date],
            t.Payment_Amount AS [Payment], 
            t.Total_Amount AS [Amount], 
            dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D1, @D0,(ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0))
            ) AS [Current],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D2, @D1,0
            ) AS [30 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D3, @D2,0
            ) AS [60 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D4, @D3,0
            ) AS [90 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D5, @D4,0
            ) AS [120 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D6, @D5,0
            ) AS [150 Days],
		dbo.fn_AW_Amount_of_Date_Between
            (
                (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0)), t.Date_Captured, @D7, @D6,0
            ) AS [180+ Days]
    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
	WHERE (t.Sys_AW_Transaction_Types_ID = 8 OR    --Purchase Invoice
           t.Sys_AW_Transaction_Types_ID = 9 OR    --Purchase Refund
           t.Sys_AW_Transaction_Types_ID = 10 OR   --Purchase Journal
           t.Sys_AW_Transaction_Types_ID = 12 OR   --Supplier Payment
           t.Sys_AW_Transaction_Types_ID = 6) AND  --Supplier Settlement Discount
          (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
		  (t.AW_User_Companies_ID = @CompanyID)
    
    RETURN

END
GO
--Index On AO_GRV_Details.AP_Products_ID
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AO_GRV_Details_AP_Products_ID'
)
DROP INDEX AO_GRV_Details.IX_AO_GRV_Details_AP_Products_ID
GO
CREATE INDEX IX_AO_GRV_Details_AP_Products_ID
   ON AO_GRV_Details (AP_Products_ID)
	WITH FILLFACTOR = 80
GO
IF EXISTS
(
	SELECT 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkEnableProductBins'
	AND Control_Index = 0
	AND Control_Value = '0'
)
BEGIN
	UPDATE AP_Products_Bins
	SET On_Hand = p.On_Hand
	FROM AP_Products_Bins b
		INNER JOIN AP_Products p
			ON b.AP_Products_ID = p.AP_Products_ID
	WHERE Lup_AP_Product_Bins_ID = 1
END
Go
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_DayEnd_Product_Sales_Analysis]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Product_Sales_Analysis]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Product_Sales_Analysis
--Purpose       :Day-End Sales by Filter with Product Sales detail ONLY
--Functionality :
--Date          :2003/09/11
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--              :08/08/04 - Truncated [TranDate] field
--              :06/03/05 - Added Product_Code [Code] field
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
--2004.5.3      :04/08/11 - Modified [Ave Sell] field to reflect Net Sales Average
--              :04/08/11 - Added [UnitSelling] field to SUM Unit Price value for Average calc
--2004.5.8 RGL  :2013-02-20 - Added product group to order by clause
--RL	V6.2	2016-06-24	:Added Product Purchase Category group option
--RL	V6.2	2016-06-24	:Added Product Bin group option
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AS_DayEnd_Product_Sales_Analysis]
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @Option = 'Groups'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '
    ELSE
    IF @Option = 'Purchase Category'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Bins'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Product], '
    SET @sql = @sql + ' ISNULL(p.Product_Code, '''') AS [Code], '

    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 + ' CONVERT(CHAR(10), h.Transaction_Date, 121) AS [TranDate],  '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '


    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [UnitSelling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    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 + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
--    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Extended_Amount - d.Tax_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    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 '


    IF @Option = 'Type'
        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 @Option = 'Groups'
        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 @Option = 'Department'
        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 @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        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 @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        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 @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '
    ELSE
    IF @Option = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option = 'Bins'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins o ' +
            '        ON d.Lup_AP_Product_Bins_ID = o.Lup_AP_Product_Bins_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)'

    SET @sql = @sql +
--        ' ORDER BY [Filter], [Customer], [TranDate] '
        ' ORDER BY [Filter], [Product], [Code], [TranDate] '

--PRINT @sql

EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_AB_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_AB_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AB_Select_AB_Accounts
--Purpose       :General Ledger and Budget Accounts
--Date          :2002/02/19
--Authors       :TB
--MODS          :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :03/08/03 - Added [Account Balance]
--              :22/08/03 - Added [Movement]
--              :01/05/05 - Added [Controllable]
--              :02/05/05 - Added [AccountTypeID] to limit [Controllable]
--2004.3.7      :23/09/07 - Added [Account Group]
--              :28/09/07 - Added [Account Division]
--RL	V6.2	2016-06-24	:Added Lup_AB_Account_Types_ID
-----------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_AB_Accounts]
    (
        @AB_Accounts_ID int,
        @Company_ID int 
    )

AS

SET NOCOUNT ON

    SELECT
        a.AB_Accounts_ID AS [ID], 
        a.[Description] AS [Description], 
        a.Account_Number AS [Account Number], 
        a.Sys_AB_Account_Categories_ID AS [Account Categories], 
        b.Sys_AB_I1_ID AS [AccountTypeID],
        a.Sys_AW_Tax_Codes_ID AS [Tax Code],
        a.Lup_AB_Cost_Centers_ID AS [Cost Centers],
        a.Lup_AB_Account_Divisions_ID AS [Account Division],
        a.Lup_AB_Account_Groups_ID AS [Account Group],
        a.Slu_AW_Active_ID AS [Active], 
        a.AB_Account_Balance AS [Account Balance], 
        a.Opening_Balance AS [Opening Balance], 
        ISNULL(a.AB_Account_Balance, 0) - ISNULL(a.Opening_Balance, 0) AS [Movement],
        a.AW_YesNo_Controllable_ID AS [Controllable],
        a.Date_Captured AS [Date Captured], 
        a.[User_ID] AS [User ID],
        a.AW_User_Companies_ID AS [Company ID],
        a.Lup_AB_Account_Departments_ID  AS [Account Department]      
    FROM AB_Accounts a
        INNER JOIN Sys_AB_Account_Categories b
            ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID
    WHERE a.AB_Accounts_ID = @AB_Accounts_ID AND
          a.AW_User_Companies_ID = @Company_ID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_GL_Accounts_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_GL_Accounts_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AB_Select_GL_Accounts_Lups
--Purpose       :Returns the General Ledger UI Lups
--Date          :2002/02/17
--Authors       :TB
--MODS          :19/07/02 - Added Months with SHORT Description
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :01/05/05 - Added @Choice = 9 Yes/No
--              :19/02/06 - Added @Choice = 10 Transaction Code
--2004.3.7      :23/09/07 - Added @Choice = 11 GL Account Group
--              :28/09/07 - Added @Choice = 12 GL Account Division
--              :01/10/07 - Removed ORDER BY in GL Division and Group to seperate
--              :           SALES from EXPENSE accounts in list
--2004.4.4      :10/04/09 - Added @Choice = 13 User Name
--RL	V6.2	2016-06-24	:Added @Choice = 14 Lup_AB_Account_Departments_ID
--------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_GL_Accounts_Lups]
    (
    	@Choice tinyint
    )

AS

SET NOCOUNT ON

	--> Account Categories
	IF @Choice = 1
		SELECT Sys_AB_Account_Categories_ID AS [ID],
			  [Description] AS [Account Categories]
		FROM Sys_AB_Account_Categories		
		ORDER BY [Description]	

	--> Tax Codes
	ELSE 
	IF @Choice = 2
		SELECT Sys_AW_Tax_Codes_ID AS [ID],
			[Description] AS [Tax Code]
		FROM Sys_AW_Tax_Codes

	--> Cost Centers
	ELSE 
	IF @Choice = 3
		SELECT Lup_AB_Cost_Centers_ID AS [ID],
			[Description] AS [Cost Centers]
		FROM Lup_AB_Cost_Centers
		ORDER BY [Description]	

	--> Active
	ELSE 
	IF @Choice = 4
		SELECT Slu_AW_Active_ID AS [ID],
			[Description] AS [Active]
		FROM Slu_AW_Active

	--> Transaction Types
	ELSE 
	IF @Choice = 5
		SELECT Sys_AB_Transaction_Types_ID AS [ID],
			[Description] AS [Transaction_Types]
		FROM Sys_AB_Transaction_Types

    --> Years
    ELSE
    IF @Choice = 6
    	SELECT Slu_AW_Years_ID AS [ID], 
        	[Description] AS [Year] 
    	FROM Slu_AW_Years

    --> Months (Long Description)
    ELSE 
    IF @Choice = 7
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Long_Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Months (Short Description)
    ELSE 
    IF @Choice = 8
    	SELECT Slu_AW_Months_ID AS [ID], 
        	[Description] AS [Month] 
    	FROM Slu_AW_Months

    --> Yes/No
    ELSE
    IF @Choice = 9
    	SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [YesNo] 
    	FROM Slu_AW_YesNo

	--> Transaction Code
	ELSE 
	IF @Choice = 10
		SELECT Sys_AB_Transaction_Types_ID AS [ID],
			Transaction_Code AS [TranCode]
		FROM Sys_AB_Transaction_Types

	--> GL Account Group
	ELSE 
	IF @Choice = 11
		SELECT Lup_AB_Account_Groups_ID AS [ID],
			[Description] AS [GL Group]
		FROM Lup_AB_Account_Groups
--		ORDER BY [Description]

	--> GL Account Division
	ELSE 
	IF @Choice = 12
		SELECT Lup_AB_Account_Divisions_ID AS [ID],
			[Description] AS [GL Division]
		FROM Lup_AB_Account_Divisions
--		ORDER BY [Description]

	--> User
	ELSE 
	IF @Choice = 13
        SELECT AW_Users_ID AS [ID],
               Surname + ISNULL(', ' + Firstname, '') AS [User]
        FROM AW_Users
        ORDER BY [User]
        
	--> GL Account Department
	ELSE 
	IF @Choice = 14
		SELECT Lup_AB_Account_Departments_ID AS [ID],
			[Description] AS [GL Department]
		FROM Lup_AB_Account_Departments
		ORDER BY [Description]

SET NOCOUNT OFF
GO
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
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [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,
        @GroupByDepartment tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)
            
	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		Level1							varchar(100), '
	SET @sql = @sql + '		Level2							varchar(100), '
	SET @sql = @sql + '		Level3							varchar(100), '
	SET @sql = @sql + '		Level4							varchar(100), '
	SET @sql = @sql + '		Account							varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int '		
	SET @sql = @sql + ') '	


--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 = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Account, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '
	SET @sql = @sql + '		Sys_AB_I2_ID, '
	SET @sql = @sql + '		Sys_AB_I3_ID, '
	SET @sql = @sql + '		Sys_AB_I4_ID '
	SET @sql = @sql + ' ) '
		
    SET @sql = @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 + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '    
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    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 + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID] '

    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 + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_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 + ''''
            --Needs to be same period as the rest of the report RL	V6.2
		    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 + ''''
            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 + ''''
            --Needs to be same period as the rest of the report RL	V6.2
		    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 + ''''
            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

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		Department AS [Department] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, ' 
		SET @sql = @sql + '          Account   '   
	END
	ELSE
	BEGIN    
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
	        
		SET @sql = @sql + ' SELECT '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Account, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '    
		SET @sql = @sql + '          Account '                
	    
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, ' 
		SET @sql = @sql + '          Account   '       
	END
	
EXEC (@sql)


SET NOCOUNT OFF
GO
--Alter AS_Transaction_Details Table - Add Lup_AP_Product_Bins_ID
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='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AS_Transaction_Details ADD Lup_AP_Product_Bins_ID Integer
GO

UPDATE AS_Transaction_Details
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transaction_Details].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Trial_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Trial_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Trial_Balance
--Purpose       :GL Trial Balance Report data
--Functionality :Shows PERIOD BALANCES for the PRIOR Periods
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :23/10/02 - NEW version: Added Current & Prior 2 months
--              :           for all ACTIVE AB_GL_Transactions
--              :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
--              :10/03/03 - Replaced 'Balance' query section with the Balance
--              :           Sheet retrieval method which distinquises between
--              :           Balance Sheet and Income/Expense accounts and uses
--              :           a seperate WHERE clause criteria for each
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--              :29/12/04 - Added @SortOrder parameter and [GLAccountNo] field
--2004.2.7      :07/02/06 - Added new [TranCount] field to count # of GL Transaction
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Trial_Balance]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @SortOrder tinyint,
		@GroupByDepartment tinyint
        
--         @IgnoreZeroTrans tinyint,
--         @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

--Declare @GroupByDepartment tinyint        
--SET @GroupByDepartment = 1

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccount						varchar(100), '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		TranCount						int '
	SET @sql = @sql + ') '	


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


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


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

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth2ID, @PriorYear2ID)
    SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth1ID, @PriorYear1ID)
    SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccount, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		TranCount '
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' r.Lup_AB_Account_Departments_ID AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    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 '
    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) <= ' + '''' + @Period1 + ''''
    SET @sql = @sql + '         ) '
    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 '
    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) <= ' + '''' + @Period2 + ''''
    SET @sql = @sql + '         ) '
    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 '
    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) <= ' + '''' + @Period3 + ''''
    SET @sql = @sql + '         ) '
    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 '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '


    SET @sql = @sql + ' ( '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [TranCount] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		TranCount AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl   '

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY GLAccountID ASC '
			END
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccount = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		SUM(TranCount) AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY CompanyID, '
		SET @sql = @sql + '			 GLAccountID, '
		SET @sql = @sql + '			 GLAccount, '
		SET @sql = @sql + '			 GLAccountNo, '
		SET @sql = @sql + '			 GLCategory '		

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY CONVERT(VARCHAR(10),GLAccountID) + ISNULL([GLAccount], '''') ASC '
			END
	
	END
	
	--Select @sql
    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Trial_Balance_Movement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Trial_Balance_Movement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Trial_Balance
--Purpose       :GL Trial Balance Report data
--Functionality :Shows PERIOD MOVEMENT for the PRIOR Periods
--Date          :2002/01/12
--Authors       :TB
--Version       :1.0.0
--MODS:         :23/10/02 - NEW version: Added Current & Prior 2 months
--              :           for all ACTIVE AB_GL_Transactions
--              :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
--              :10/03/03 - Replaced 'Balance' query section with the Balance
--              :           Sheet retrieval method which distinquises between
--              :           Balance Sheet and Income/Expense accounts and uses
--              :           a seperate WHERE clause criteria for each
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--              :29/12/04 - Added @SortOrder parameter and [GLAccountNo] field
--2004.2.7      :07/02/06 - Added new [TranCount] field to count # of GL Transaction
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Trial_Balance_Movement]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @SortOrder tinyint,
		@GroupByDepartment tinyint
--         @IgnoreZeroTrans tinyint,
--         @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON
--Declare @GroupByDepartment tinyint        
--SET @GroupByDepartment = 1

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccount						varchar(100), '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		Prior2							decimal(18,3), '
	SET @sql = @sql + '		Prior1							decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '
	SET @sql = @sql + '		TranCount						int '
	SET @sql = @sql + ') '	

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


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


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

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth2ID, @PriorYear2ID)
    SET @Period2 = dbo.fn_AB_Get_Ending_GL_Period(@PriorMonth1ID, @PriorYear1ID)
    SET @Period3 = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccount, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		Prior2, '
	SET @sql = @sql + '		Prior1, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		TranCount '
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' r.Lup_AB_Account_Departments_ID AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [Department], '


    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)
    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)
    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)
    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 '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '


    SET @sql = @sql + ' ( '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [TranCount] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID)


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		Prior2 AS [Prior2], '
		SET @sql = @sql + '		Prior1 AS [Prior1], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		TranCount AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl   '

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY GLAccountID ASC '
			END
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccount = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		CompanyID AS [CompanyID], '
		SET @sql = @sql + '		GLAccountID AS [GLAccountID], '
		SET @sql = @sql + '		GLAccount AS [GLAccount], '
		SET @sql = @sql + '		GLAccountNo AS [GLAccountNo], '
		SET @sql = @sql + '		GLCategory AS [GLCategory], '
		SET @sql = @sql + '		SUM(Prior2) AS [Prior2], '
		SET @sql = @sql + '		SUM(Prior1) AS [Prior1], '
		SET @sql = @sql + '		SUM([Current]) AS [Current], '
		SET @sql = @sql + '		SUM(Balance) AS [Balance], '
		SET @sql = @sql + '		SUM(TranCount) AS [TranCount] '
		SET @sql = @sql + ' FROM @Tbl '
		SET @sql = @sql + ' GROUP BY CompanyID, '
		SET @sql = @sql + '			 GLAccountID, '
		SET @sql = @sql + '			 GLAccount, '
		SET @sql = @sql + '			 GLAccountNo, '
		SET @sql = @sql + '			 GLCategory '		

		IF @SortOrder = 0
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 1
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL(GLAccountNo, '''') ASC '
			END

		ELSE
		IF @SortOrder = 2
			BEGIN
				SET @sql = @sql + ' ORDER BY ISNULL([GLCategory], '''') + ISNULL([GLAccount], '''') ASC '
			END

		ELSE
		IF @SortOrder = 3
			BEGIN
				SET @sql = @sql + ' ORDER BY CONVERT(VARCHAR(10),GLAccountID) + ISNULL([GLAccount], '''') ASC '
			END
	
	END

    EXEC (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Casing_Credit_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Casing_Credit_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Casing_Credit_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Casing Credit Refund)
--              :1. UPDATES AS_Transactions: Total_Cost
--              :2. UPDATES On_Hand and Average Cost for all JOB Products 
--              :3. INSERTS Non-GL Stock Adjustments for all JOB Products
--              :NB NB - NO GL ENTRIES ARE REQUIRED BECAUSE EXTERNAL PROCEDURES
--              :        (Day-End) WRITE ALL REQUIRED GL ENTRIES AUTOMATICALLY
--Functionality :AS_Transactions types with Detail only: 4
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2011/05/10
--Authors       :TB
--MODS          :
--2004.5.2      :04/07/11 - Added an additional Adjustment (Type 1 Qty) to deduct the stock
--              :           that was added by the Customer Refund for Credit Credit
--              :06/07/11 - Reworked and checked ALL calculations and DB updates
--              :10/07/11 - Added GL Postings to audit trail inventory movement
--              :           especially important in SPLIT CONTINOUS INVENTORY
--              :13/07/11 - Replaced @JobTicketID with @JobNo in @Note text
--2004.5.5      :17/10/11 - Fixed UPDATE Header Tran Total_Cost section that set the Total_Cost =
--              :           the COST OF THE CURRENT PRODUCT being inserted !! (No MULTIPLES CREDITS)
--              :           and DID NOT ADD EACH PRODUCT COST to the Total_Cost of the Doc Header 
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Casing_Credit_Insert]
    (
		@DocumentID int,
		@JobTicketID int,
        @CasingProductID int,
        @StockProductID int,
		@Qty decimal(9,3),
		@CasingCredit 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 @AdjustmentsID int,
    		@OriginalPrice money,
            @SmallMake varchar(6),
            @RepairProductID int,
            @OtherProductID int,
            @RetreadCost money,
            @RepairCost money,
            @OtherCost money,
            @FactoryCosts money,
            @TotalCost money,
            @PurchasesControlGLID int,
            @InventoryControlGLID int,
            @CasingCode varchar(20),
            @RepairCode varchar(20),
            @OtherCode varchar(20),
            @StockCode varchar(20),
            @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_LastCostTotal money,
            @Prev_AvgCostTotal money,
            @New_Last_Cost money,
            @New_Average_Cost money,
        	@New_On_Hand decimal(9,3),
            @New_LastCostTotal money,
            @New_AvgCostTotal money,
            @AdjustmentType tinyint,
            @User_Name varchar(40),
            @Note varchar(70),
            @GRVID int,
            @InvoiceNo varchar(20),
            @RefundNo varchar(19),
            @NoCI tinyint,
            @NormalCI tinyint,
            @SplitCI tinyint,
            @CasingTypeDesc varchar(50),
            @RepairTypeDesc varchar(50),
            @OtherTypeDesc varchar(50),
            @StockTypeDesc varchar(50),
            @CasingGLDesc varchar(50),
            @RepairGLDesc varchar(50),
            @OtherGLDesc varchar(50),
            @StockGLDesc varchar(50),
            @GLCasingID int,
            @GLRepairID int,
            @GLOtherID int,
            @GLStockID int,
            @Narration varchar(50),
            @TempRef varchar(20),
            @InsertGLTran bit,
            @TempCost money,
            @TempCasingCredit money,
            @MonthID tinyint,
            @YearID int,
            @OppositeQty decimal(9,3)


    SELECT @RefundNo = ISNULL(Transaction_Number, '')
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @DocumentID


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


    ---------------------------------------------------------------------------
    --> UPDATE Header Tran Total_Cost - Qty and Amounts SIGN REVERSAL DONE IN UI
    ---------------------------------------------------------------------------
--     UPDATE AS_Transactions
--     SET Total_Cost = -@CasingCredit
--     WHERE AS_Transactions_ID = @DocumentID

    -- NEW 2004.5.5 - Fixed to enable MULTIPLE CREDITS on ONE REFUND
    SET @TempCasingCredit = ABS(@CasingCredit) * -1

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


	SELECT @OriginalPrice = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate())
	FROM AP_Products
	WHERE AP_Products_ID = @CasingProductID


---------------------------------------------------------------------------
--> Do the CUSTOMER REFUND
---------------------------------------------------------------------------
	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,
			@CasingProductID,
			-@Qty,
			@CasingCredit,
			@CasingCredit,
			@OriginalPrice,
			-@Tax,
			-@Total,
            @JobNo,
            @SmallMake,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)


    --> Add Refund Qty to Product On_Hand
    IF @CasingProductID > 0
        BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand + @Qty
            WHERE AP_Products_ID = @CasingProductID
        END
        
	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		EXEC sp_AP_Products_Bins_Update_Insert 
			@CasingProductID,	--@ProductID int,
			1,					--@ProductBinID int,
    		@Qty,				--@Qty decimal(9,3)
    		'F CASCRED',		--@Source varchar(10),
    		0,					--@Batch_No
    		@UserID,			--@UserID int,
    		@CompanyID			--@CompanyID int
	END	
        
---------------------------------------------------------------------------


---------------------------------------------------------------------------
--> Do the STOCK ADJUSTMENTS
---------------------------------------------------------------------------

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


    --> Get the Job Ticket info - CHECK if ANY LOCKS on the record !!
    SELECT @RepairProductID =ISNULL(AP_Repair_Products_ID, 0),
           @OtherProductID = ISNULL(AP_Other_Products_ID, 0),
           @RetreadCost = ISNULL(Retread_Cost, 0),
           @RepairCost = ISNULL(Repair_Cost, 0),
           @OtherCost = ISNULL(Other_Cost, 0),
           @GRVID =  ISNULL(AO_GRV_ID, 0),
           @InvoiceNo = ISNULL(Invoice_No, '')
    FROM AF_Job_Tickets
    WHERE AF_Job_Tickets_ID = @JobTicketID

    SET @FactoryCosts = @RetreadCost + @RepairCost + @OtherCost
    SET @TotalCost = @FactoryCosts + @CasingCredit

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0


    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @CasingProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the CASING (Retread) Product stuff
            ---------------------------------------------------------------------------
        	SELECT @CasingCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @CasingProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

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

            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

            ---------------------------------------------------------------------------
            --> ADJUST Factory GRV Stock of CASING PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @CasingProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@CasingProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit GRVFAC Adjustment ' + @InvoiceNo + '(' + CONVERT(varchar(10), @GRVID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 


        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @CasingProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
            ---------------------------------------------------------------------------

            ---------------------------------------------------------------------------
            --> ADJUST Customer Refund Stock of CASING PRODUCT
            ---------------------------------------------------------------------------
            ---------------------------------------------------------------------------
            --> Prepare values for Qty Adjustment (costs must remain same as above)
            ---------------------------------------------------------------------------
            SET @Prev_On_Hand = @New_On_Hand
            SET @New_On_Hand = @Prev_On_Hand - @Qty

        	UPDATE AP_Products 
        	SET On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @CasingProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@CasingProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 1
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 

        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @CasingProductID,
                    @AdjustmentType,
        			@CasingCredit,
                    @CasingCredit,
        			@Prev_On_Hand ,
        			@CasingCredit,
                    @CasingCredit,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
            ---------------------------------------------------------------------------

        END
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @RepairProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the REPAIR Product stuff
            ---------------------------------------------------------------------------
        	SELECT @RepairCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @RepairProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

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

            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

            ---------------------------------------------------------------------------
            --> ADJUST Stock of REPAIR PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @RepairProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@RepairProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 


        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @RepairProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
        END
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF @OtherProductID > 0
        BEGIN
            ---------------------------------------------------------------------------
            --> Get the OTHER Product stuff
            ---------------------------------------------------------------------------
        	SELECT @OtherCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
                   @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
                   @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
        		   @Prev_On_Hand = ISNULL(On_Hand, 0)
        	FROM AP_Products
        	WHERE AP_Products_ID = @OtherProductID

            ---------------------------------------------------------------------------
            --> Calculate AVERAGE COST (lifted from Stock Returns)
            ---------------------------------------------------------------------------
            SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
            SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

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

            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

            ---------------------------------------------------------------------------
            --> ADJUST Stock of OTHER PRODUCT
            ---------------------------------------------------------------------------
        	UPDATE AP_Products 
        	SET Average_Cost = @New_Average_Cost,
                On_Hand = On_Hand - @Qty
        	WHERE AP_Products_ID = @OtherProductID

			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@OtherProductID,	--@ProductID int,
					1,					--@ProductBinID int,
    				@OppositeQty,				--@Qty decimal(9,3)
    				'F CASCRED',		--@Source varchar(10),
    				0,					--@Batch_No
    				@UserID,			--@UserID int,
    				@CompanyID			--@CompanyID int
			END	

            SET @AdjustmentType = 6
            SET @Note = 'Casing Credit REFUND Adjustment ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
            SET @Note = LEFT(@Note, 70) 

        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID,
        			Lup_AP_Product_Bins_ID
                )
        	VALUES
                (
                    @OtherProductID,
                    @AdjustmentType,
        			@Prev_Last_Cost,
                    @Prev_Average_Cost,
        			@Prev_On_Hand ,
        			@Prev_Last_Cost,
                    @New_Average_Cost,
        			@New_On_Hand,
        			@Note,
        			getdate(),
        			@UserID,
        			@CompanyID,
        			1 --Defaulted to 1
                )
        END
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    --> Do the STOCK Product ADJUSTMENT
    ---------------------------------------------------------------------------

    SET @Prev_LastCostTotal = 0
    SET @Prev_AvgCostTotal = 0
    SET @New_LastCostTotal = 0
    SET @New_AvgCostTotal = 0
    SET @New_On_Hand = 0
    SET @New_Average_Cost = 0
    SET @New_Last_Cost = 0

    ---------------------------------------------------------------------------
    --> Get the STOCK Product stuff
    ---------------------------------------------------------------------------
    SELECT @StockCode = RTRIM(LTRIM(LEFT(ISNULL(Product_Code, ''), 20))),
           @Prev_Average_Cost = ABS(ISNULL(Average_Cost, 0)),
           @Prev_Last_Cost = ABS(ISNULL(Last_Cost, 0)),
		   @Prev_On_Hand = ISNULL(On_Hand, 0)
	FROM AP_Products
	WHERE AP_Products_ID = @StockProductID

    ---------------------------------------------------------------------------
    --> Calculate AVERAGE COST (lifted from Stock Returns)
    ---------------------------------------------------------------------------
    SET @Prev_LastCostTotal = @Prev_Last_Cost * @Prev_On_Hand
    SET @Prev_AvgCostTotal = @Prev_Average_Cost * @Prev_On_Hand

    SET @New_LastCostTotal = @Prev_LastCostTotal + @TotalCost
    SET @New_AvgCostTotal = @Prev_AvgCostTotal + @TotalCost

    SET @New_On_Hand = @Prev_On_Hand + @Qty
    SET @New_Last_Cost = @TotalCost

    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

    ---------------------------------------------------------------------------
    --> ADJUST Stock of STOCK PRODUCT
    ---------------------------------------------------------------------------
	UPDATE AP_Products 
	SET Last_Cost = @New_Last_Cost,
        Average_Cost = @New_Average_Cost,
        On_Hand = On_Hand + @Qty  
	WHERE AP_Products_ID = @StockProductID

	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		--Roadmaster Incorrect sign
		--SET @OppositeQty = @Qty * -1
		EXEC sp_AP_Products_Bins_Update_Insert 
			@StockProductID,	--@ProductID int,
			1,					--@ProductBinID int,
			@Qty,				--@Qty decimal(9,3)
			'F CASCRED',		--@Source varchar(10),
			0,					--@Batch_No
			@UserID,			--@UserID int,
			@CompanyID			--@CompanyID int
	END	

    SET @AdjustmentType = 6
    SET @Note = 'Casing Credit TRF to STOCK Adjustment C/N ' + @RefundNo + '(' + CONVERT(varchar(10), @DocumentID) + ')' + ' Job No ' + CONVERT(varchar(10), @JobNo) + ' (No GL update)'
    SET @Note = LEFT(@Note, 70) 
    SET @AdjustmentsID = 0


	INSERT INTO AP_Inventory_Adjustments
        (
			AP_Products_ID,
            Sys_AP_Adjustment_Types_ID,
			Previous_Last_Cost,
            Previous_Average_Cost,
			Previous_On_Hand,
			New_Last_Cost,
            New_Average_Cost,
			New_On_Hand,
			Note,
			Date_Captured,
			[User_ID],
			AW_User_Companies_ID,
        	Lup_AP_Product_Bins_ID
        )
	VALUES
        (
            @StockProductID,
            @AdjustmentType,
			@Prev_Last_Cost,
            @Prev_Average_Cost,
			@Prev_On_Hand ,
			@New_Last_Cost,
            @New_Average_Cost,
			@New_On_Hand,
			@Note,
			getdate(),
			@UserID,
			@CompanyID,
        	1 --Defaulted to 1
        )

    SELECT @AdjustmentsID = SCOPE_IDENTITY() 
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    -- NOW DO INVENTORY ACCOUNT TRF GL Transactions
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------


    ---------------------------------------------------------------------------
    -- TRF from SOURCE INVENTORY account and put to TARGET INVENTORY account
    ---------------------------------------------------------------------------

    --    DR:    STOCK PRODUCT     -->    @FactoryCosts
    --    CR:    CASING PRODUCT    -->    @RetreadCost
    --    CR:    REPAIR PRODUCT    -->    @RepairCost
    --    CR:    OTHER PRODUCT     -->    @OtherCost
    ----------------------------------------------------------------
    -- If @SplitCI the Day-End handles the REFUND like this:
    --        Debits    Casing Refund to    INVENTORY - Casings
    --        Credits   Casing Refund to    C.O.S. - Casings 
    ----------------------------------------------------------------
    -- We must transfer the inventory like this:
    --    DR:    STOCK PRODUCT     -->    @CasingCredit
    --    CR:    CASING PRODUCT    -->    @CasingCredit
 
    --    Day-End will handle the REFUND (@CasingCredit) GL Transactions
    ---------------------------------------------------------------------------

    ---------------------------------------------------------------------
    --> Get NORMAL Continuous Inventory STOCK RECEIPTS parameter setting
    ---------------------------------------------------------------------
    SET @NormalCI = '0'

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

    ---------------------------------------------------------------------
    --> Get SPLIT Continuous Inventory STOCK RECEIPTS parameter setting
    ---------------------------------------------------------------------
    SET @SplitCI = '0'

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


    ---------------------------------------------------------------------
    --> Get NO Continuous Inventory is used then use PURCHASES CONTROl
    ---------------------------------------------------------------------
    SET @NoCI = 0

    IF @NormalCI = 0 AND @SplitCI = 0
        BEGIN
            SET @NoCI = 1
        END

    ---------------------------------------------------------------------
    --> Get the PURCHASES CONTROL if NO Continuous Inventory
    ---------------------------------------------------------------------
    SELECT @PurchasesControlGLID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 301        --Purchases Control

    ---------------------------------------------------------------------
    --> Get the INVENTORY CONTROL if NOT Split Continuous Inventory
    ---------------------------------------------------------------------
    SELECT @InventoryControlGLID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 601        --Inventory Control
    ---------------------------------------------------------------------

    SELECT @MonthID = ISNULL(Slu_AW_Months_ID, 1),
           @YearID = ISNULL(Slu_AW_Years_ID, 1)
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID


    SET @TempCost = 0
    SET @InsertGLTran = 0              --0 = Do Not insert a GL Transaction in JNL Details
    SET @Narration = 'Casing Credit Inventory TRF Job No ' + CONVERT(varchar(10), @JobNo)
    SET @Narration = LEFT(@Narration, 50)


    ---------------------------------------------------------------------
    --> INSERT GL INVENTORY TRF Tran for CASING PRODUCT here
    ---------------------------------------------------------------------

    --> Create GL TRANSACTIONS for SPLIT Inventory
    IF @SplitCI = 1
        BEGIN
            --> Get the CASING PRODUCT TYPE and SET GL Description
            IF @CasingProductID > 0
                BEGIN
                    SET @CasingTypeDesc = ''

        			SELECT @CasingTypeDesc = 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 = @CasingProductID

                    SET @CasingGLDesc = LEFT('INVENTORY - ' + @CasingTypeDesc, 50)
                END

            --> Get the REPAIR PRODUCT TYPE and SET GL Description
            IF @RepairProductID > 0
                BEGIN
                    SET @RepairTypeDesc = ''

        			SELECT @RepairTypeDesc = 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 = @RepairProductID

                    SET @RepairGLDesc = LEFT('INVENTORY - ' + @RepairTypeDesc, 50)
                END

            --> Get the OTHER PRODUCT TYPE and SET GL Description
            IF @OtherProductID > 0
                BEGIN
                    SET @OtherTypeDesc = ''

        			SELECT @OtherTypeDesc = 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 = @OtherProductID

                    SET @OtherGLDesc = LEFT('INVENTORY - ' + @OtherTypeDesc, 50)
                END

            --> Get the STOCK PRODUCT TYPE and SET GL Description
            IF @StockProductID > 0
                BEGIN
                    SET @StockTypeDesc = ''

        			SELECT @StockTypeDesc = 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 = @StockProductID

                    SET @StockGLDesc = LEFT('INVENTORY - ' + @StockTypeDesc, 50)
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Casing Product
            ---------------------------------------------------------------------
            IF @CasingProductID > 0
                BEGIN
                    SET @GLCasingID = 0

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

                    IF @GLCasingID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLCasingID = sp_AB_Insert_System_GL_Account
                                                    @CasingGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Repair Product
            ---------------------------------------------------------------------
            IF @RepairProductID > 0
                BEGIN
                    SET @GLRepairID = 0

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

                    IF @GLRepairID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLRepairID = sp_AB_Insert_System_GL_Account
                                                    @RepairGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Other Product
            ---------------------------------------------------------------------
            IF @OtherProductID > 0
                BEGIN
                    SET @GLOtherID = 0

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

                    IF @GLOtherID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLOtherID = sp_AB_Insert_System_GL_Account
                                                    @OtherGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END

            ---------------------------------------------------------------------
            --> GET or CREATE SPLIT GL INVENTORY AccountID for Other Product
            ---------------------------------------------------------------------
            IF @StockProductID > 0
                BEGIN
                    SET @GLStockID = 0

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

                    IF @GLStockID = 0            --CREATE a NEW GL Account
                        BEGIN
             				EXEC @GLStockID = sp_AB_Insert_System_GL_Account
                                                    @StockGLDesc,
                                                    7,
                                                    @UserID,
                                                    @CompanyID
                        END
                END
            ---------------------------------------------------------------------

            SET @TempCost = @RetreadCost * -1

            IF @CasingProductID > 0
                BEGIN
                    SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCasingID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            SET @TempCost = @RepairCost * -1

            IF @RepairProductID > 0
                BEGIN
                    SET @TempRef = @RepairCode + '(' + CONVERT(varchar(10), @RepairProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLRepairID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            SET @TempCost = @OtherCost * -1

            IF @OtherProductID > 0
                BEGIN
                    SET @TempRef = @OtherCode + '(' + CONVERT(varchar(10), @OtherProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLOtherID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END

            IF @StockProductID > 0
                BEGIN
                    SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLStockID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @FactoryCosts,
                            @UserID,
                            @CompanyID
                END


            ----------------------------------------------------------------
            -- If @SplitCI the Day-End handles the REFUND like this:
            --        Debits    Casing Refund to    INVENTORY - Casings
            --        Credits   Casing Refund to    C.O.S. - Casings 
            ----------------------------------------------------------------
            -- We must transfer the inventory like this:
            --    DR:    STOCK PRODUCT     -->    @CasingCredit
            --    CR:    CASING PRODUCT    -->    @CasingCredit
            ----------------------------------------------------------------

            SET @Narration = 'Casing Refund Day-End Inventory TRF Job No ' + CONVERT(varchar(10), @JobNo)
            SET @Narration = LEFT(@Narration, 50)

            SET @TempCost = @CasingCredit * -1

            IF @CasingProductID > 0
                BEGIN
                    SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLCasingID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @TempCost,
                            @UserID,
                            @CompanyID
                END


            IF @StockProductID > 0
                BEGIN
                    SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
                    SET @TempRef = LEFT(@TempRef, 20)

                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            15,
                            @GLStockID,
                            @DatePosted,
                            @TempRef,
                            @MonthID,
                            @YearID,
                            @JobTicketID,
                            @CasingCredit,
                            @UserID,
                            @CompanyID
                END


        END        --IF @SplitCI = 1
        ------------------------------------------------------------------------------

    --> Create GL TRANSACTION for Purchases Control 301 - IN and OUT
    ELSE
    IF @NoCI = 1
        BEGIN
            SET @TempCost = @FactoryCosts * -1

            SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @PurchasesControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @TempCost,
                    @UserID,
                    @CompanyID


            SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @PurchasesControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @FactoryCosts,
                    @UserID,
                    @CompanyID
        END
        ------------------------------------------------------------------------------

    --> DEFAULT - Create GL TRANSACTION for Inventory Control 601 - IN and OUT
    ELSE        --> @NormalCI = 1 - NORMAL CONTINUOUS INVENTORY
        BEGIN
            SET @TempCost = @FactoryCosts * -1

            SET @TempRef = @CasingCode + '(' + CONVERT(varchar(10), @CasingProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @InventoryControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @TempCost,
                    @UserID,
                    @CompanyID


            SET @TempRef = @StockCode + '(' + CONVERT(varchar(10), @StockProductID) + ')'
            SET @TempRef = LEFT(@TempRef, 20)

            EXEC sp_AB_Insert_GL_Transactions
                    @Narration,
                    15,
                    @InventoryControlGLID,
                    @DatePosted,
                    @TempRef,
                    @MonthID,
                    @YearID,
                    @JobTicketID,
                    @FactoryCosts,
                    @UserID,
                    @CompanyID
        END    
        ------------------------------------------------------------------------------

RETURN @AdjustmentsID
GO
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.2 RL	2016-06-26	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [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),
        	@OppositeQty decimal(9,3)

    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
 
		--Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SET @OppositeQty = @Qty * -1
			EXEC sp_AP_Products_Bins_Update_Insert 
				@AP_Products_ID,	--@ProductID int,
				1,					--@ProductBinID int,
    			@Qty,				--@Qty decimal(9,3)
    			'GRN',				--@Source varchar(10),
    			0,					--@Batch_No
    			@UserID,			--@UserID int,
    			@CompanyID			--@CompanyID int
		END	
    
		--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,
        				Lup_AP_Product_Bins_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,
            			1 --Defaulted to 1
                    )

         --   END
    
    END
GO
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
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [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,
            			Lup_AP_Product_Bins_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,
            			1 --Defaulted to 1
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    
    END 			

SET NOCOUNT OFF
GO
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
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [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,
        			Lup_AP_Product_Bins_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,
        			1 --Defaulted to 1
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO
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
--V6.2 RL	2016-06-25	:Added Product Bins
--------------------------------------------------------------------------------

CREATE PROCEDURE [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,
        			Lup_AP_Product_Bins_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,
        			1 --Defaulted to 1
                )

        	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
        END


    RETURN @AdjustmentsID

SET NOCOUNT OFF
GO
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [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) + ''
	
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 31'		--Consignment Goods Received
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 32'		--Consignment Goods Returned
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 34'		--Consignment Sold

	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
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [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) + ''
	
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 31'		--Consignment Goods Received
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 32'		--Consignment Goods Returned
	SET @sql = @sql + ' AND gh.Sys_AW_Transaction_Types_ID <> 34'		--Consignment Sold

	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
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AO_Department_Purchases]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AO_Department_Purchases]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AO_Department_Purchases
--Purpose       :Retrieves Ad-Hoc Purchases data for Purchase by Department
--Tables        :
--Parameters    :
--Date          :2002/11/28
--Authors       :TB
--Version       :1.0.0
--MODS          :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
--              :02/01/03 - Modified to COMPARE from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period with @Period* vars
--              :02/01/03 - Added [Month] and [Year] fields to SELECT
--              :15/04/04 - Added GRV field
--              :10/01/05 - Removed DISTINCT filter (Maureen) preventing multiples
--              :           of the same item printing on the report
--V6.2	RL	2016-07-01	:Excluded consignment GRV's
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AO_Department_Purchases]
    (
        @MonthID tinyint,
        @YearID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Period1 varchar(6)

    SET @Period1 = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

--    SELECT DISTINCT
    SELECT
        t.AO_Suppliers_ID AS [ID], 
        pd.Lup_AP_Product_Departments_ID AS [DeptID],
        ISNULL(pd.[Description], '') AS [DeptName],
        ISNULL(s.Supplier_Name, '') AS [Supplier],
        ISNULL(t.Document_Date, '') AS [Date], 
        ISNULL(t.Document_Number, '') AS [Ref No],
        ISNULL(tt.Type_Code, '') AS [Type], 
        ISNULL(gl.[Description], '') AS [GL Account],

        t.Slu_AW_Months_ID AS [Month],
        t.Slu_AW_Years_ID AS [Year],

        ISNULL(p.[Description], '') AS [Product],
        ISNULL(t.AO_GRV_ID, 0) AS [GRV],
        ISNULL(gd.Qty, 0) AS [Qty],
        ISNULL(gd.Unit_Price, 0) AS [Unit Price],
        ISNULL(gd.Trade_Discount_Amount, 0) AS [Trade],
        ISNULL(gd.Rebate_Discount_Amount, 0) AS [Rebate],
        ISNULL(gd.Other_Discount_Amount, 0) AS [Other],
        ISNULL(gd.Net_Amount, 0) AS [Sub-Total],
        ISNULL(gd.Tax_Amount, 0) AS [Tax],
        ISNULL(gd.Total_Cost, 0) AS [Total],

        dbo.GetGrossMargin
            (
                p.Price1_Effective_Date,
                p.Price1_Price1,
                p.Price2_Effective_Date,
                p.Price2_Price1,
                getdate(),
                p.Last_Cost
            ) as [GP %]

    FROM AO_Transactions t
        LEFT JOIN AO_Suppliers s
            ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
        LEFT OUTER JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
        LEFT JOIN AB_Accounts gl
            ON t.AB_Accounts_ID = gl.AB_Accounts_ID
        INNER JOIN AO_GRV gh
            ON t.AO_GRV_ID = gh.AO_GRV_ID
        INNER JOIN AO_GRV_Details gd
            On gh.AO_GRV_ID = gd.AO_GRV_ID
        INNER JOIN AP_Products p
            ON gd.AP_Products_ID = p.AP_Products_ID
        INNER JOIN Lup_AP_Product_Departments pd
            ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID

    WHERE t.AW_User_Companies_ID = @CompanyID AND
          dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) = @Period1 AND
--           t.Slu_AW_Months_ID = @MonthID AND
--           t.Slu_AW_Years_ID = @YearID
			gh.Sys_AW_Transaction_Types_ID <> 31 AND		--Consignment Goods Received
			gh.Sys_AW_Transaction_Types_ID <> 32 AND		--Consignment Goods Returned
			gh.Sys_AW_Transaction_Types_ID <> 34			--Consignment Sold

    ORDER BY pd.Lup_AP_Product_Departments_ID,
             t.AO_Suppliers_ID,             
             ISNULL(t.Document_Date, '')


SET NOCOUNT OFF
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AP_Products_Bins]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
--Drop TABLE [AP_Products_Bins]
	CREATE TABLE [AP_Products_Bins]
	(
		[AP_Products_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[On_Hand] decimal(9,3) NOT NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		CONSTRAINT [PK_AP_Products_Bins] PRIMARY KEY CLUSTERED 
		(
			[AP_Products_Bins_ID] ASC
		)
	)
END
GO

	EXECUTE sp_bindefault N'[dbo].[df_Date_Captured]', N'[dbo].[Lup_AP_Product_Bins].[Date_Captured]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_User_ID]', N'[dbo].[Lup_AP_Product_Bins].[User_ID]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_User_Companies]', N'[dbo].[Lup_AP_Product_Bins].[AW_User_Companies_ID]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_Active]', N'[dbo].[Lup_AP_Product_Bins].[Slu_AW_Active_ID]'
	GO

	--AO_Suppliers Change Default of Use_Supplier_Discount_Defaults
	EXECUTE sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[dbo].[AO_Suppliers].[Use_Supplier_Discount_Defaults]'
	GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Received_GRV]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Received_GRV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Received_GRV
--Purpose       :Fetches all GRV that have already been received for the specified supplier 
--Functionality :SELECT 
--Parameters    :@Supplier_ID
--Date          :2001/10/02
--Authors       :TB
--MODS          :
--2004.3.8      :30/05/08 - Added [GRV] field
--              :30/05/08 - Renamed [Orders ID] field to [Order]
--V6.2	RL	2016-07-07	:Added order by GRV_ID Descending
--------------------------------------------------------------------------------

CREATE Procedure [sp_AO_Select_Received_GRV]
    (
    	@SupplierID int = 0,
    	@Company_ID int			
    )

AS

	BEGIN
	
		SELECT AO_GRV_ID AS [ID],
    			Sys_AW_Transaction_Types_ID,
    			AO_Suppliers_ID AS [Suppliers ID],
    			AO_Orders_ID AS [Order],
                AO_GRV_ID AS [GRV],
    			Date_Received AS [Date Received],
    			Delivery_Note_Number AS [Del Note No],
    			Supplier_Reference AS [Suppliers Ref],
    			Trade_Discount_Total AS [Trade Disc],
    			Rebate_Discount_Total AS [Rebate Disc],
    			Other_Discount_Total AS [Other Disc],
    			Net_Amount AS [Net],
    			Total_Tax_Amount AS [Tax],
    			Total_Amount AS [Total],
    			Date_Captured AS [Date Captured],
    			[User_ID] AS [User ID],
    			AW_User_Companies_ID AS [Company],
    			Slu_AW_Active_ID AS [Active]
		FROM AO_GRV g
		WHERE AO_Suppliers_ID = @SupplierID AND
			Sys_AW_Transaction_Types_ID = 19 AND
			AW_User_Companies_ID = @Company_ID
		ORDER BY AO_GRV_ID DESC
		
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AF_Refund_Job_No_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AF_Refund_Job_No_Detail_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AF_Refund_Job_No_Detail_Insert
--Purpose       :INSERTS CUSTOMER Refund Job No DETAILS (from Invoice Details)
--              :    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/08/28
--Authors       :TB
--MODS          :
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AF_Refund_Job_No_Detail_Insert]
    (
		@DocumentID int,
		@ProductID int,
		@Qty decimal(9,3),
		@UnitCost money,
		@UnitPrice money,
		@OrigPrice money,
		@OrigDisc money,
		@Discount money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
        @JobRefID int,
        @Make varchar(6),
        @SerialNo varchar(13),
        @Customer varchar(20),
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
        	@OppositeQty decimal(9,3)


    SET @DocumentDetailsID = 0


    ---------------------------------------------------------------------------
    --> UPDATE Product - Qty and Amounts SIGN REVERSAL DONE IN UI (Set as NEGATIVE)
    ---------------------------------------------------------------------------
    UPDATE AP_Products
    SET On_Hand = On_Hand + -@Qty
    WHERE AP_Products_ID = @ProductID
    ---------------------------------------------------------------------------

	--Update Bin Qty
	IF @Qty <> 0
	BEGIN
		SET @OppositeQty = @Qty * -1
		EXEC sp_AP_Products_Bins_Update_Insert 
			@ProductID,	--@ProductID int,
			1,					--@ProductBinID int,
			@OppositeQty,		--@Qty decimal(9,3)
			'GRN',				--@Source varchar(10),
			0,					--@Batch_No
			@UserID,			--@UserID int,
			@CompanyID			--@CompanyID int
	END	
    
	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
            Original_Discount,
            Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			@Qty,
			@UnitCost,
			@UnitPrice,
			@OrigPrice,
            @OrigDisc,
            @Discount,
			@Tax,
			@Total,
            @JobRefID,
            @Make,
            @SerialNo,
            @Customer,
            @DatePosted,
			@UserID,
			@CompanyID
		)

	SELECT @DocumentDetailsID = Scope_Identity()



RETURN @DocumentDetailsID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Detail_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Detail_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Insert
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS (Periodic 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/01/20
--Authors       :TB
--MODS          :
--V6.2 RL	2016-06-26	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AS_Transaction_Detail_Insert]
    (
		@DocumentID int,
		@TranTypeID int,
		@ProductID int,
        @CostMethod tinyint,
		@Qty decimal(9,3),
		@UnitPrice money,
		@Amount money,
		@Tax money,
        @Total money,
        @DatePosted datetime,
		@UserID int,
		@CompanyID int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID int,
            @Cost money,
            @TotalCost money,
    		@OriginalPrice money,
        	@OppositeQty decimal(9,3)


    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 = @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()
            WHERE AP_Products_ID = @ProductID
            
			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,			--@ProductID int,
					1,					--@ProductBinID int,
					@OppositeQty,		--@Qty decimal(9,3)
					'SALE',				--@Source varchar(10),
					0,					--@Batch_No
					@UserID,			--@UserID int,
					@CompanyID			--@CompanyID int
			END	
            
		END

	ELSE
	IF @TranTypeID = 4    --> Refund
		BEGIN
            UPDATE AP_Products
            SET On_Hand = On_Hand - @Qty
            WHERE AP_Products_ID = @ProductID
            
			--Update Bin Qty
			IF @Qty <> 0
			BEGIN
				SET @OppositeQty = @Qty * -1
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,			--@ProductID int,
					1,					--@ProductBinID int,
					@OppositeQty,		--@Qty decimal(9,3)
					'CN',				--@Source varchar(10),
					0,					--@Batch_No
					@UserID,			--@UserID int,
					@CompanyID			--@CompanyID int
			END	
            
		END


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

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

	SELECT @DocumentDetailsID = Scope_Identity()



RETURN @DocumentDetailsID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Transactions_Payments_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Transactions_Payments_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Transactions_Payments_Select
--Purpose       :Supplier Payments: Unpaid Remittance Transactions
--Date          :2002/01/12
--Authors       :TB 
--Mods          :13/06/02 - Added additional info for each transaction and
--              :           removed Date_Captured
--              :30/10/02 - Added Month & Year to Unpaid Transactions grid
--              :04/11/02 - Added retrieving only specific Transaction Types
--              :04/11/02 - Added Ageing parameters and Ageing retrieval
--              :           from fn_AO_Supplier_Period_Ageing
--              :16/12/03 - Added NEW Settlement_Discount to @Choice = 2
--2004.4.7      :17/09/09 - Added to select unallocated Payment transactions
--              :           (TranType = 12) for new Lumpsum Payments
--V6.2	RL	2016/07/14	:Added Document_Date to order by
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AO_Transactions_Payments_Select]

    (
        @Choice tinyint,
        @SupplierID int,
    	@M1 tinyint,
    	@Y1 int,
    	@M2 tinyint,
    	@Y2 int,
    	@M3 tinyint,
    	@Y3 int,
    	@M4 tinyint,
    	@Y4 int,
    	@M5 tinyint,
    	@Y5 int,
    	@M6 tinyint,
    	@Y6 int,
    	@M7 tinyint,
    	@Y7 int
    )

AS

SET NOCOUNT ON

--> SUPPLIER CATALOG: Account Balances tab (Ageing Totals)
	IF @Choice = 1
        BEGIN
            SELECT
             	[SupplierID],
            	[Payment],
            	[Amount],
            	[Current],
            	[30 Days],
            	[60 Days],
            	[90 Days],
            	[120 Days], 
            	[150 Days],
            	[180+ Days]
            FROM dbo.fn_AO_Supplier_Period_Ageing_Values
                    (
                    	@SupplierID, 
                    	@M1, @Y1,
                    	@M2, @Y2,
                    	@M3, @Y3,
                    	@M4, @Y4,
                    	@M5, @Y5,
                    	@M6, @Y6,
                    	@M7, @Y7
                    ) 
		END

---------------------------------------------------------------------------------------
--> SUPPLIER PAYMENTS: Unpaid Transactions
    IF @Choice = 2
        BEGIN

            SELECT
                t.AO_Transactions_ID AS [ID], 
                t.AO_Suppliers_ID AS [Supplier_ID], 
                t.To_Be_Paid AS [Pay], 
                t.To_Be_Paid_Amount AS [To Pay],
                t.Settlement_Discount AS [Settlement],
                t.Remittance_Balance AS [Balance], 
                ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) as [Owing], 
                tt.[Description] AS [Type],
                t.Document_Number AS [Ref No],
                t.Document_Date AS [Date], 
                m.[Description] AS [Month],
                y.[Description] AS [Year],
                t.Total_Amount AS [Total],
                t.Payment_Amount AS [Paid],
                t.AO_GRV_ID AS [GRV],
                gr.AO_Orders_ID AS [Order],
                u.[UserName] AS [User],
        --NB: IF ANY COLUMNS ARE ADDED BEFORE AGEING BELOW, MODIFY HIDEROWS ORDINAL POSITION
        		a.[Current],
        		a.[30 Days],
        		a.[60 Days],
        		a.[90 Days],
        		a.[120 Days],
        		a.[150 Days],
        		a.[180+ Days]
        	FROM AO_Transactions t
                LEFT JOIN dbo.fn_AO_Supplier_Period_Ageing
                            (
                            	@SupplierID, 
                            	@M1, @Y1,
                            	@M2, @Y2,
                            	@M3, @Y3,
                            	@M4, @Y4,
                            	@M5, @Y5,
                            	@M6, @Y6,
                            	@M7, @Y7
                            ) a
                    ON t.AO_Transactions_ID = a.[ID]
                LEFT JOIN Sys_AW_Transaction_Types tt
                    ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
                LEFT JOIN AO_GRV gr
                    ON t.AO_GRV_ID = gr.AO_GRV_ID
                LEFT JOIN AW_Users u
                    ON t.[User_ID] = u.AW_Users_ID
                LEFT JOIN Slu_AW_Months m
                    ON t.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                LEFT JOIN Slu_AW_Years y
                    ON t.Slu_AW_Years_ID = y.Slu_AW_Years_ID
        	WHERE t.AO_Suppliers_ID = @SupplierID AND
                 (ISNULL(t.Total_Amount,0) + ISNULL(t.Payment_Amount,0) <> 0) AND
                 (t.Sys_AW_Transaction_Types_ID = 6 OR        --Supplier Settlement
                  t.Sys_AW_Transaction_Types_ID = 8 OR        --Supplier Invoice
                  t.Sys_AW_Transaction_Types_ID = 9 OR        --Supplier Refund
                  t.Sys_AW_Transaction_Types_ID = 10 OR       --Supplier Journal
                  t.Sys_AW_Transaction_Types_ID = 12)         --Supplier Payment
            ORDER BY t.Slu_AW_Years_ID, t.Slu_AW_Months_ID, t.Document_Date
        END


SET NOCOUNT OFF
GO

--Truncate Table AP_Products_Bins

--Fix products were Products not in AP_Products_Bins 
INSERT INTO AP_Products_Bins
(
	AP_Products_ID, 
	Lup_AP_Product_Bins_ID, 
	On_Hand, 
	Date_Captured, 
	[User_ID], 
	AW_User_Companies_ID, 
	Slu_AW_Active_ID
)
SELECT 
	AP_Products_ID, 
	1,			--Default Bin
	On_Hand, 
	Date_Captured, 
	[User_ID], 
	AW_User_Companies_ID, 
	Slu_AW_Active_ID
FROM AP_Products WHERE AP_products_ID NOT IN (SELECT AP_products_ID FROM AP_Products_Bins) 
GO
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AP_Products_INS' 
    AND type = 'TR'
)
DROP TRIGGER trg_AP_Products_INS
GO
CREATE TRIGGER [trg_AP_Products_INS] ON [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     
   
	IF NOT EXISTS
	(
		SELECT 1
		FROM AP_Products_Bins
		WHERE AP_Products_ID = (SELECT AP_Products_ID FROM Inserted)
	)
	BEGIN
		INSERT INTO AP_Products_Bins
		(
			AP_Products_ID, 
			Lup_AP_Product_Bins_ID, 
			On_Hand, 
			Date_Captured, 
			User_ID, 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID
		)
		SELECT
			AP_Products_ID,
			1,		--Default Bin
			On_Hand,
			GetDate(),
			[User_ID],
			AW_User_Companies_ID,
			Slu_AW_Active_ID
		FROM Inserted				
	END
     
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Man_Acc]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Man_Acc]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Man_Acc
--Purpose       :GAAP Management Accounts Report
--Parameters    :
--Date          :2002/12/10
--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
--              :09/04/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.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Man_Acc]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)
            
--Declare @GroupByDepartment tinyint
--Set @GroupByDepartment = 1

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '	
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	


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


	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '



    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    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 + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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  [CurrentTot], '

    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), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '

    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    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 Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '


    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 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 + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_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 + '         ) '
            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 + '         ) '
            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, '
--------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '								
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '								
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Accounts
--Purpose       :Management Accounts Report
--Parameters    :
--Date          :2004/06/13
--Authors       :TB
--Version       :1.0.0
--MODS:         :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.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Management_Accounts]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
	@GroupByDepartment tinyint        
    )

AS

SET NOCOUNT ON

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '
	SET @sql = @sql + '		Budget							decimal(18,3), '		
	SET @sql = @sql + '		YTDBudgetTot					decimal(18,3), '
	SET @sql = @sql + '		YTDBudget						decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '	
	SET @sql = @sql + '		Balance							decimal(18,3) '		
	SET @sql = @sql + ') '	


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

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '	
	SET @sql = @sql + '		YTDBudgetTot, '
	SET @sql = @sql + '		YTDBudget, '	
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        

    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 + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '            --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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  [CurrentTot], '


    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), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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(bud.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets bud '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON bud.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '            --Only Income Statement accounts
    SET @sql = @sql + '           bud.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           bud.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(bud.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets bud '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON bud.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '                --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(bud.Slu_AW_Months_ID, bud.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS  [YTDBudgetTot], '

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget], '

    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '                --Only Income Statement accounts
    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 Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '


    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 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 + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_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 + '         ) '
            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 + '         ) '
            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, '
-------------------------------------------------------------------------------------------
--09/04/03 - Added ORDER BY AB_Accounts.Description to display all report category accounts 
    SET @sql = @sql + '          a.Description   '
-------------------------------------------------------------------------------------------

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '		
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '
		SET @sql = @sql + '		YTDBudgetTot AS [YTDBudgetTot], '
		SET @sql = @sql + '		YTDBudget AS [YTDBudget], '		
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '		
		SET @sql = @sql + '		SUM(ISNULL(YTDBudgetTot,0)) AS [YTDBudgetTot], '								
		SET @sql = @sql + '		SUM(ISNULL(YTDBudget,0)) AS [YTDBudget], '
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '		
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Management_Account_Groups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Management_Account_Groups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Account_Groups
--Purpose       :Management Accounts GROUP BY GL Account Group Report
--Parameters    :
--Date          :2007/09/23
--Authors       :TB
--MODS:         :
--2004.4.4      :08/05/09 - Added b.Sys_AB_I4_ID in Sort Order IF @CombineSalesCOS = 1
--              :           to DISPLAY SALES ACCOUNTS FIRST in Group lists
--              :08/05/09 - Reworked @IgnoreZeroTrans and @IgnoreZeroBalance sections to
--              :           prevent loss of accounts with ZERO Current but with a Balance
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Management_Account_Groups]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @CombineSalesCOS tinyint,
        @GroupByDepartment tinyint
    )

AS

SET NOCOUNT ON

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

--Declare @GroupByDepartment tinyint
--Set @GroupByDepartment = 0

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLID							int, '
	SET @sql = @sql + '		AccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	SET @sql = @sql + '		GLDivision						varchar(100), '	
	SET @sql = @sql + '		GLGroup							varchar(100), '			
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	SET @sql = @sql + '		DivisionID						int, '			
	SET @sql = @sql + '		GroupID							int, '					
	
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		YTDBudget						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	

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

    ------------------------------------------------
    -- Get the DESCRIPTION of the Revenue Category
    ------------------------------------------------
    SELECT @RevenueCategory = Description
    FROM Sys_AB_Account_Categories
    WHERE Sys_AB_Account_Categories_ID = 13
    ------------------------------------------------

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLID, '
	SET @sql = @sql + '		AccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '
	SET @sql = @sql + '		GLDivision, '
	SET @sql = @sql + '		GLGroup, '		

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	SET @sql = @sql + '		DivisionID, '
	SET @sql = @sql + '		GroupID, '		
	
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		Budget, '	
	SET @sql = @sql + '		YTDBudget, '	
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '


    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [AccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    SET @sql = @sql + ' ISNULL(g.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(h.[Description], '''') AS [GLGroup], '

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

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN b.Sys_AB_Account_Categories_ID = 14 '
            SET @sql = @sql + '      THEN ''' + @RevenueCategory + ''' '
            SET @sql = @sql + '      ELSE ISNULL(b.[Description], '''') '
            SET @sql = @sql + ' END AS [Level4], ' 
        END
    ELSE
         BEGIN
            SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [Level4], '
         END
    
	SET @sql = @sql + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '


--    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Divisions_ID AS [DivisionID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Groups_ID AS [GroupID], '


    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), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)

    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(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget], '


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

    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND 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 + '     LEFT JOIN Lup_AB_Account_Divisions g '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = g.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups h '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = h.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
   

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND 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 + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            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 + '         ) '
            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 + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            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 + '         ) '
            SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

            IF @IgnoreYEJnl = 1
                BEGIN
                    SET @sql = @sql + '          AND Sys_AB_Transaction_Types_ID <> 16'
                END
            SET @sql = @sql + '         ) '
            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, '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
        END

    SET @sql = @sql + '          g.[Description], '
    SET @sql = @sql + '          h.[Description], '

    IF @CombineSalesCOS = 1
        BEGIN
            --------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            --------------------------------------------------------------

            SET @sql = @sql + '          a.Account_Number, '
        END

    SET @sql = @sql + '          a.Description   '


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '

		
		SET @sql = @sql + '		Sys_AB_I4_ID AS [IS4ID], '
		SET @sql = @sql + '		GLID AS [GLID], '
		SET @sql = @sql + '		DivisionID AS [DivisionID], '						
		SET @sql = @sql + '		GroupID AS [GroupID], '								
		
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		AccountNo AS [AccountNo], '
		SET @sql = @sql + '		GLDivision AS [GLDivision], '
		SET @sql = @sql + '		GLGroup AS [GLGroup], '		
		
		SET @sql = @sql + '		ISNULL([Current],0) AS [Current], '
		SET @sql = @sql + '		ISNULL([Budget],0) AS [Budget], '
		SET @sql = @sql + '		ISNULL([YTDBudget],0) AS [YTDBudget], '
		SET @sql = @sql + '		ISNULL([Balance],0) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '

	    IF @CombineSalesCOS = 1
		    BEGIN
			    SET @sql = @sql + '          [Level4], '
			END
		ELSE
			BEGIN
				SET @sql = @sql + '          Sys_AB_I4_ID, '
			END

		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '			 GLGroup, '

		IF @CombineSalesCOS = 1
			BEGIN
				--------------------------------------------------------------
				--> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
				SET @sql = @sql + '          Sys_AB_I4_ID, '
				--------------------------------------------------------------

				SET @sql = @sql + '          AccountNo, '
			END

	    SET @sql = @sql + '          Account   '

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLID = 1, '
		SET @sql = @sql + '		AccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		AccountNo AS [AccountNo], '
		SET @sql = @sql + '		GLDivision AS [GLDivision], '
		SET @sql = @sql + '		GLGroup AS [GLGroup], '		
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL([Budget],0)) AS [Budget], '
		SET @sql = @sql + '		SUM(ISNULL([YTDBudget],0)) AS [YTDBudget], '		
		SET @sql = @sql + '		SUM(ISNULL([Balance],0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account, '
		SET @sql = @sql + '          AccountNo, '		
		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '          GLGroup '				
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '

	    IF @CombineSalesCOS = 1
		    BEGIN
			    SET @sql = @sql + '          [Level4], '
			END
		ELSE
			BEGIN
				SET @sql = @sql + '          Sys_AB_I4_ID, '
			END

		SET @sql = @sql + '          GLDivision, '
		SET @sql = @sql + '			 GLGroup, '

		IF @CombineSalesCOS = 1
			BEGIN
				--------------------------------------------------------------
				--> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
				SET @sql = @sql + '          Sys_AB_I4_ID, '
				--------------------------------------------------------------

				SET @sql = @sql + '          AccountNo, '
			END

	    SET @sql = @sql + '          Account   '
	
	END

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Balance_Sheet]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Balance_Sheet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Balance_Sheet
--Purpose       :GAAP Balance Sheet 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
--              :16/10/03 - Modified TOTAL INCOME AND EXPENSE account balance
--              :           (at the ending period) to TOTAL OF ALL TRANSACTIONS
--              :           from the system start (see note below)
--              :26/03/04 - Modified [Balance] field to fetch account totals up
--              :           to @EndPeriod for ALL accounts not only BS accounts
--2004.2.5      :21/11/05 - Added option @IgnoreZeroTrans and @IgnoreZeroBalance
--              :           to ignore accounts with no entries and/or zero balances
--2004.3.8      :10/04/08 - Increased @sql to 8000
--              :11/04/08 - Commented [TranCount] not used
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Balance_Sheet]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint        
    )

AS

SET NOCOUNT ON

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_B1_ID					int, '
	SET @sql = @sql + '		Sys_AB_B2_ID					int, '
	SET @sql = @sql + '		Sys_AB_B3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		Balance							decimal(18,3) '	
	SET @sql = @sql + ') '	


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


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


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

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	--SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_B1_ID, '	
	SET @sql = @sql + '		Sys_AB_B2_ID, '	
	SET @sql = @sql + '		Sys_AB_B3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		Balance '	
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    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 + ' b.Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
	SET @sql = @sql + ' b.Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
	SET @sql = @sql + ' b.Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '

-- --NEW 21/11/05----------------------------------
--     SET @sql = @sql + ' ( '
--     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 + '         ) '
--     SET @sql = @sql + ' ) AS [TranCount], '
-- ------------------------------------------------


--NEW 26/03/04----------------------------------
    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 '
    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 + '         ) '
    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_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '
    

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


    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 + '         ) '
            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 + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '


	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		Balance AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance] '
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
--		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_B1_ID, '		
		SET @sql = @sql + '          Sys_AB_B2_ID, '		
		SET @sql = @sql + '          Sys_AB_B3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

    EXEC (@sql)

SET NOCOUNT OFF
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AP_Products_Bins_History]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN

-- Drop TABLE [AP_Products_Bins_History]
	CREATE TABLE [AP_Products_Bins_History]
	(
		[AP_Products_Bins_History_ID] [int] IDENTITY(1,1) NOT NULL,
		[Batch_No] [int] NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[From_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[From_Bin_Previous_On_Hand] decimal(9,3) NOT NULL,
		[From_Bin_New_On_Hand] decimal(9,3) NOT NULL,
		[To_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[To_Bin_Previous_On_Hand] decimal(9,3) NOT NULL,
		[To_Bin_New_On_Hand] decimal(9,3) NOT NULL,
		[Movement_Source] varchar(10) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		CONSTRAINT [PK_AP_Products_Bins_History] PRIMARY KEY CLUSTERED 
		(
			[AP_Products_Bins_History_ID] ASC
		)
	)
END
GO

	EXECUTE sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Products_Bins_History].[Movement_Source]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_Date_Captured]', N'[dbo].[Lup_AP_Product_Bins].[Date_Captured]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_User_ID]', N'[dbo].[Lup_AP_Product_Bins].[User_ID]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_User_Companies]', N'[dbo].[Lup_AP_Product_Bins].[AW_User_Companies_ID]'
	GO
	EXECUTE sp_bindefault N'[dbo].[df_Active]', N'[dbo].[Lup_AP_Product_Bins].[Slu_AW_Active_ID]'
	GO

INSERT INTO AP_Products_Bins
(
	AP_Products_ID,
	Lup_AP_Product_Bins_ID,
	On_Hand,
	Date_Captured,
	[User_ID],
	AW_User_Companies_ID,
	Slu_AW_Active_ID
)
SELECT
	AP_Products_ID,
	1, --Default
	On_Hand,
	GETDATE(),
	1,
	1,
	1
FROM AP_Products
WHERE AP_Products_ID NOT IN (
								SELECT AP_Products_ID
								FROM AP_Products_Bins
							)	
GO

INSERT INTO AP_Products_Bins_History
(
	Batch_No,
	AP_Products_ID,
	From_Lup_AP_Product_Bins_ID,
	From_Bin_Previous_On_Hand,
	From_Bin_New_On_Hand,
	To_Lup_AP_Product_Bins_ID,
	To_Bin_Previous_On_Hand,
	To_Bin_New_On_Hand,
	Movement_Source,
	Date_Captured,
	[User_ID],
	AW_User_Companies_ID,
	Slu_AW_Active_ID
)
SELECT
	1,
	AP_Products_ID,
	1, --Default
	0,
	On_Hand,
	1, --Default
	0,
	On_Hand,
	'SYSTEM',	
	GETDATE(),
	1,
	1,
	1
FROM AP_Products
WHERE On_Hand <> 0
AND AP_Products_ID NOT IN (
								SELECT AP_Products_ID
								FROM AP_Products_Bins_History
						   )	
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AP_Products_Bins_AP_Products_ID'
)
DROP INDEX AP_Products_Bins.IX_AP_Products_Bins_AP_Products_ID
GO
CREATE INDEX IX_AP_Products_Bins_AP_Products_ID
   ON AP_Products_Bins (AP_Products_ID)
	WITH FILLFACTOR = 80
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AP_Products_Bins_History_AP_Products_ID'
)
DROP INDEX AP_Products_Bins_History.IX_AP_Products_Bins_History_AP_Products_ID
GO
CREATE INDEX IX_AP_Products_Bins_History_AP_Products_ID
   ON AP_Products_Bins_History (AP_Products_ID)
	WITH FILLFACTOR = 80
GO

--Create Index on AP_Products_Audit.AP_Products_ID
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AP_Products_Audit_AP_Products_ID'
)
DROP INDEX AP_Products_Audit.IX_AP_Products_Audit_AP_Products_ID
GO
CREATE INDEX IX_AP_Products_Audit_AP_Products_ID
   ON AP_Products_Audit (AP_Products_ID)
	WITH FILLFACTOR = 80
GO

--AP_Products_Audit.Changes_Sent
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_Audit' AND
        C.Name='Changes_Sent'
)
ALTER TABLE AP_Products_Audit ADD Changes_Sent int NULL
GO
	
UPDATE AP_Products_Audit
SET Changes_Sent = 0
WHERE ISNULL(Changes_Sent,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Audit].[Changes_Sent]'
-------------------------------------------------------
GO

--Create Index on AP_Products_Audit.Changes_Sent
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'Ind_AP_Products_Audit_Changes_Sent'
)
DROP INDEX AP_Products_Audit.Ind_AP_Products_Audit_Changes_Sent
GO
CREATE INDEX Ind_AP_Products_Audit_Changes_Sent
   ON AP_Products_Audit (Changes_Sent)
	WITH FILLFACTOR = 80
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'PK_AP_Products_Audit'
)
BEGIN
	ALTER TABLE [dbo].[AP_Products_Audit] DROP Constraint PK_AP_Products_Audit
END
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'AP_Products_Audit_ID'
)                 
BEGIN
	ALTER TABLE [dbo].[AP_Products_Audit] DROP Constraint AP_Products_Audit_ID
END
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'PK_AP_Products_Audit_ID'
)
BEGIN
	ALTER TABLE [dbo].[AP_Products_Audit] DROP Constraint PK_AP_Products_Audit_ID
END
GO


--Create Index on AP_Products_Audit.Changes_Sent
IF NOT EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'PK_AP_Products_Audit_ID'
)
BEGIN
    ALTER TABLE [dbo].[AP_Products_Audit] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Audit_ID] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Audit_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
END    
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Balance_Sheet_Comparative]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Balance_Sheet_Comparative]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Balance_Sheet
--Purpose       :GAAP Comparative Balance Sheet Report
--Parameters    :
--Date          :2008/04/11
--Authors       :TB
--MODS:         :2008/04/11 - Ignore Zero Trans and Balance accounts not allowed
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Balance_Sheet_Comparative]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @GroupByDepartment tinyint                
    )

AS

SET NOCOUNT ON

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_B1_ID					int, '
	SET @sql = @sql + '		Sys_AB_B2_ID					int, '
	SET @sql = @sql + '		Sys_AB_B3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		Balance							decimal(18,3), '	
	SET @sql = @sql + '		PrevBalance						decimal(18,3) '		
	SET @sql = @sql + ') '	

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


-------------------------------------------------------------------------------
--> NEW 16/10/2003 mod
-------------------------------------------------------------------------------
-->     The rationale is as follows:
--        EVEN FOR INCOME AND EXPENSE ACCOUNTS, the account balance at the end
--            of any period (as with ASSET and LIABILITY accounts) is equal to the
--            TOTAL OF ALL TRANSACTIONS up the the end of the period, because
--            account totals are zeroed in any event during Year-End GL procedures.
--            This also takes care of situations where none or erratic GL procedures
--            are (or are not) done spanning multiple fiscal periods.
-------------------------------------------------------------------------------
    --> Initialize the SYSTEM Start Month and Year (in case there are no AB_GL_Transactions)
        SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID
        FROM Slu_AW_Months
        ORDER BY Slu_AW_Months_ID
        
        SELECT TOP 1 @StartYearID = Slu_AW_Years_ID
        FROM Slu_AW_Years
        ORDER BY Slu_AW_Years_ID

    --> Initialize the Start Month and Year (from OLDEST in AB_GL_Transactions)
        IF EXISTS
            (
                SELECT TOP 1 Slu_AW_Months_ID, Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            )
            BEGIN
                SELECT TOP 1 @StartMonthID = Slu_AW_Months_ID,
                             @StartYearID = Slu_AW_Years_ID
                FROM AB_GL_Transactions
                ORDER BY Slu_AW_Months_ID, Slu_AW_Years_ID
            END
-------------------------------------------------------------------------------
--> END 16/10/2003 mod
-------------------------------------------------------------------------------


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


    SET @LastYearID = @CurrentYearID - 1
    SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
    SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @LastYearID)


	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	--SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_B1_ID, '	
	SET @sql = @sql + '		Sys_AB_B2_ID, '	
	SET @sql = @sql + '		Sys_AB_B3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		Balance, '
	SET @sql = @sql + '		PrevBalance '
	SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '        
    
    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 + ' b.Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
	SET @sql = @sql + ' b.Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
	SET @sql = @sql + ' b.Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
-- ------------------------------------------------
--     SET @sql = @sql + ' ( '
--     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 + '         ) '
--     SET @sql = @sql + ' ) AS [TranCount], '
-- ------------------------------------------------


------------------------------------------------
    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 '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [Balance], '
------------------------------------------------


------------------------------------------------
    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 '
    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) <= ' + '''' + @LastEndPeriod + ''''
    SET @sql = @sql + '         ) '
    SET @sql = @sql + ' ) AS [PrevBalance] '
------------------------------------------------


    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_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '

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


--     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 + '         ) '
--             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 + '         ) '
--             SET @sql = @sql + ' ) <> 0 '
-- 
--         END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		PrevBalance AS [PrevBalance] '		
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
--		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_B1_ID AS [Sys_AB_B1_ID], '
		SET @sql = @sql + '		Sys_AB_B2_ID AS [Sys_AB_B2_ID], '
		SET @sql = @sql + '		Sys_AB_B3_ID AS [Sys_AB_B3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance], '
		SET @sql = @sql + '		SUM(ISNULL(PrevBalance,0)) AS [PrevBalance] '		
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
--		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_B1_ID, '		
		SET @sql = @sql + '          Sys_AB_B2_ID, '		
		SET @sql = @sql + '          Sys_AB_B3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
		SET @sql = @sql + '          Sys_AB_B2_ID, '
		SET @sql = @sql + '          Sys_AB_B3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END


    EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Income_Statement_Comparative]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Income_Statement_Comparative]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Income_Statement_Comparative
--Purpose       :GAAP Comparative Income Statement Report
--Parameters    :
--Date          :2008/04/10
--Authors       :TB
--MODS:         :11/04/08 - Ignore Zero Trans and Balance accounts not allowed
--2004.4.3      :13/03/09 - Fixed method to set @LastStartPeriod and @LastEndPeriod
--              :13/03/09 - Added @PeriodOption for MOVING 12 MONTHS or FISCAL YEAR-TO-DATE
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Income_Statement_Comparative]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @PeriodOption tinyint,
        @GroupByDepartment tinyint
    )

AS

SET NOCOUNT ON

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

	SET @sql = 'DECLARE @Tbl Table '
	SET @sql = @sql + '( '
	SET @sql = @sql + '		CompanyID						int, '
	SET @sql = @sql + '		GLAccountID						int, '
	SET @sql = @sql + '		GLAccountNo						varchar(100), '
	SET @sql = @sql + '		GLCategory						varchar(100), '	
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID	int, '
	SET @sql = @sql + '		Department						varchar(100), '	
	
	SET @sql = @sql + '		Level1							varchar(100), '	
	SET @sql = @sql + '		Level2							varchar(100), '	
	SET @sql = @sql + '		Level3							varchar(100), '	
	SET @sql = @sql + '		Level4							varchar(100), '				
	SET @sql = @sql + '		Sys_AB_I1_ID					int, '
	SET @sql = @sql + '		Sys_AB_I2_ID					int, '
	SET @sql = @sql + '		Sys_AB_I3_ID					int, '
	SET @sql = @sql + '		Sys_AB_I4_ID					int, '			
	SET @sql = @sql + '		Account							varchar(100), '
	
	SET @sql = @sql + '		CurrentTot						decimal(18,3), '
	SET @sql = @sql + '		[Current]						decimal(18,3), '
	SET @sql = @sql + '		BudgetTot						decimal(18,3), '	
	SET @sql = @sql + '		Budget							decimal(18,3), '
	SET @sql = @sql + '		BalanceTot						decimal(18,3), '
	SET @sql = @sql + '		Balance							decimal(18,3), '	
	SET @sql = @sql + '		PrevTot							decimal(18,3), '	
	SET @sql = @sql + '		PrevBalance						decimal(18,3) '	
	SET @sql = @sql + ') '	

    IF @PeriodOption = 0
        BEGIN
            ----------------------------------------------------------------------------------------
            -- Get PERIODS for MOVING 12 MONTHS
            ----------------------------------------------------------------------------------------
            SET @StartMonthID = @MonthID + 1
            SET @StartYearID = @YearID - 1

            IF @StartMonthID = 13
                BEGIN
                    SET @StartMonthID = 1
                    SET @StartYearID = @StartYearID + 1
                END

            SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
            SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)

            SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, (@StartYearID - 1))
            SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID - 1)
            ----------------------------------------------------------------------------------------
        END
    ELSE
    IF @PeriodOption = 1
        BEGIN
            ----------------------------------------------------------------------------------------
            -- Get PERIODS for FISCAL YEAR-TO-DATE
            ----------------------------------------------------------------------------------------
            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)

            SET @LastStartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID - 1)
            SET @LastEndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID - 1)
            ----------------------------------------------------------------------------------------
        END

	SET @sql = @sql + ' INSERT INTO @Tbl '
	SET @sql = @sql + ' ( '
	SET @sql = @sql + '		CompanyID, '
	SET @sql = @sql + '		GLAccountID, '
	SET @sql = @sql + '		GLAccountNo, '
	SET @sql = @sql + '		GLCategory, '
	SET @sql = @sql + '		Lup_AB_Account_Departments_ID, '
	SET @sql = @sql + '		Department, '

	SET @sql = @sql + '		Level1, '
	SET @sql = @sql + '		Level2, '
	SET @sql = @sql + '		Level3, '
	SET @sql = @sql + '		Level4, '
	SET @sql = @sql + '		Sys_AB_I1_ID, '	
	SET @sql = @sql + '		Sys_AB_I2_ID, '	
	SET @sql = @sql + '		Sys_AB_I3_ID, '	
	SET @sql = @sql + '		Sys_AB_I4_ID, '	
	SET @sql = @sql + '		Account, '
	
	SET @sql = @sql + '		CurrentTot, '
	SET @sql = @sql + '		[Current], '
	SET @sql = @sql + '		BudgetTot, '
	SET @sql = @sql + '		Budget, '
	SET @sql = @sql + '		BalanceTot, '		
	SET @sql = @sql + '		Balance, '	
	SET @sql = @sql + '		PrevTot, '		
	SET @sql = @sql + '		PrevBalance '		
	SET @sql = @sql + ' ) '
	
    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + ' ISNULL(a.AW_User_Companies_ID, 1) AS [CompanyID], '
    SET @sql = @sql + ' ISNULL(a.AB_Accounts_ID, 1) AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '    
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(r.Lup_AB_Account_Departments_ID, 1) AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
    
    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 + ' b.Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
	SET @sql = @sql + ' b.Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
	SET @sql = @sql + ' b.Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
	SET @sql = @sql + ' b.Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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  [CurrentTot], '
    ------------------------------------------------------------------------------------------------------

    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), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
--> 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.Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets t '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 AND '    --Only Income Statement accounts
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS  [BudgetTot], '
    ------------------------------------------------------------------------------------------------------

    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '
    ------------------------------------------------------------------------------------------------------

    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    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 Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [BalanceTot], '
    ------------------------------------------------------------------------------------------------------

    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 Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance], '
    ------------------------------------------------------------------------------------------------------

    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 + '     LEFT JOIN AB_Accounts a '
    SET @sql = @sql + '         ON t.AB_Accounts_ID = a.AB_Accounts_ID '
    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 + '     WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           b.Sys_AB_I4_ID = 10 '    --Only Income Statement accounts
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @LastStartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @LastEndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [PrevTot], '
    ------------------------------------------------------------------------------------------------------

    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) >= ' + '''' + @LastStartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @LastEndPeriod + ''''

--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [PrevBalance] '
    ------------------------------------------------------------------------------------------------------

    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 + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_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


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

	IF @GroupByDepartment = 0
	BEGIN
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '	
		SET @sql = @sql + '		Account AS [Account], '											
		SET @sql = @sql + '		CurrentTot AS [CurrentTot], '
		SET @sql = @sql + '		[Current] AS [Current], '
		SET @sql = @sql + '		BudgetTot AS [BudgetTot], '
		SET @sql = @sql + '		Budget AS [Budget], '								
		SET @sql = @sql + '		BalanceTot AS [BalanceTot], '
		SET @sql = @sql + '		Balance AS [Balance], '
		SET @sql = @sql + '		PrevTot AS [PrevTot], '
		SET @sql = @sql + '		PrevBalance AS [PrevBalance] '				
		SET @sql = @sql + ' FROM @Tbl   '
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		

	END
	ELSE
	BEGIN
	
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET Account = Department '
		SET @sql = @sql + ' WHERE Lup_AB_Account_Departments_ID <> 1 '
		
		SET @sql = @sql + ' UPDATE @Tbl '
		SET @sql = @sql + ' SET GLAccountID = 1, '
		SET @sql = @sql + '		GLAccountNo = '+''''' '
	
		SET @sql = @sql + ' SELECT   '
		SET @sql = @sql + '		Level1 AS [Level1], '
		SET @sql = @sql + '		Level2 AS [Level2], '
		SET @sql = @sql + '		Level3 AS [Level3], '
		SET @sql = @sql + '		Level4 AS [Level4], '
		SET @sql = @sql + '		Sys_AB_I1_ID AS [Sys_AB_I1_ID], '
		SET @sql = @sql + '		Sys_AB_I2_ID AS [Sys_AB_I2_ID], '
		SET @sql = @sql + '		Sys_AB_I3_ID AS [Sys_AB_I3_ID], '
		SET @sql = @sql + '		Sys_AB_I4_ID AS [Sys_AB_I4_ID], '
		SET @sql = @sql + '		Account AS [Account], '
		SET @sql = @sql + '		SUM(ISNULL(CurrentTot,0)) AS [CurrentTot], '
		SET @sql = @sql + '		SUM(ISNULL([Current],0)) AS [Current], '
		SET @sql = @sql + '		SUM(ISNULL(BudgetTot,0)) AS [BudgetTot], '
		SET @sql = @sql + '		SUM(ISNULL(Budget,0)) AS [Budget], '								
		SET @sql = @sql + '		SUM(ISNULL(BalanceTot,0)) AS [BalanceTot], '
		SET @sql = @sql + '		SUM(ISNULL(Balance,0)) AS [Balance], '
		SET @sql = @sql + '		SUM(ISNULL(PrevTot,0)) AS [PrevTot], '
		SET @sql = @sql + '		SUM(ISNULL(PrevBalance,0)) AS [PrevBalance] '				
		SET @sql = @sql + ' FROM @Tbl   '

		SET @sql = @sql + ' GROUP BY Level1, '
		SET @sql = @sql + '          Level2, '
		SET @sql = @sql + '          Level3, '
		SET @sql = @sql + '          Level4, '
		SET @sql = @sql + '          Sys_AB_I1_ID, '		
		SET @sql = @sql + '          Sys_AB_I2_ID, '		
		SET @sql = @sql + '          Sys_AB_I3_ID, '		
		SET @sql = @sql + '          Sys_AB_I4_ID, '						
		SET @sql = @sql + '          Account '		
						
		SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
		SET @sql = @sql + '          Sys_AB_I2_ID, '
		SET @sql = @sql + '          Sys_AB_I3_ID, '
		SET @sql = @sql + '          Sys_AB_I4_ID, '
		SET @sql = @sql + '          Account '		
	
	END

EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Drop_Enterprise_Trial_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Trial_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Trial_Balance
--Purpose       :Drops and re-creates AP_Enterprise_Trial_Balance table
--Date          :2007/08/28
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--2004.4.8      :05/11/09 - Added Divisions and Groups columns sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Trial_Balance]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Trial_Balance]

        CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
        	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Divisions] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Groups] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Trial_Balance_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Drop_Enterprise_Balance_Sheet]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Balance_Sheet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Balance_Sheet
--Purpose       :Drops and re-creates AP_Enterprise_Balance_Sheet table
--Date          :2007/09/09
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Balance_Sheet]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Balance_Sheet]

        
        CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
        	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_B1_ID] [int] NULL ,
        	[Sys_AB_B2_ID] [int] NULL ,
        	[Sys_AB_B3_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Total] [money] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Balance_Sheet_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Drop_Enterprise_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Income_Statement
--Purpose       :Drops and re-creates AP_Enterprise_Income_Statement table
--Date          :2007/09/05
--Authors       :TB
--MODS          :
--2004.3.8      :08/04/08 - Increased [Category] from [50] to [100] !!!!!
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Income_Statement]

AS

    DECLARE @ReturnValue int

    SET @ReturnValue = 0


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Income_Statement]

        
        CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
        	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Sys_AB_I1_ID] [int] NULL ,
        	[Sys_AB_I2_ID] [int] NULL ,
        	[Sys_AB_I3_ID] [int] NULL ,
        	[Sys_AB_I4_ID] [int] NULL ,
        	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,        	
        	[Total] [money] NULL
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Income_Statement_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Drop_Enterprise_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Drop_Enterprise_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Drop_Enterprise_Management_Accounts
--Purpose       :Drops and re-creates AB_Enterprise_Management_Accounts table
--Date          :2015-08-20
--Authors       :RL
--MODS          :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Drop_Enterprise_Management_Accounts]
AS

    DECLARE @ReturnValue int
    SET @ReturnValue = 0

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Enterprise_Management_Accounts]
        
        CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
        	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[IS1ID] [int] NULL ,
        	[IS2ID] [int] NULL ,        	
        	[IS3ID] [int] NULL ,        	
        	[IS4ID] [int] NULL ,
        	[GLID] [int] NULL ,
        	[DivisionID] [int] NULL ,
        	[GroupID] [int] NULL ,
        	
        	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	
        	[GLDivision] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[GLGroup] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[AccountNo] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[Account] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        	[Lup_AB_Account_Departments_ID] [int] NULL ,
        	[Department] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,       	
        	
        	[TotalActual] [money] NULL,
        	[TotalBudget] [money] NULL,
        	[TotalYTDActual] [money] NULL,
        	[TotalYTDBudget] [money] NULL        	
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Enterprise_Management_Accounts_ID]
        	)  ON [PRIMARY] 

    SET @ReturnValue = 1

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Insert_Enterprise_Trial_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Insert_Enterprise_Trial_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Trial_Balance
--Purpose       :INSERT Enterprise Trial Balance
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @Divisions and @Groups columns sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Trial_Balance]
	(
        @ColumnName						varchar(50),
        @Description					varchar(50),
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Divisions						varchar(50),
        @Groups							varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(4000),
            @eTB_ID int


    SET @eTB_ID = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @Description = ISNULL(@Description, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Divisions = ISNULL(@Divisions, '')
    SET @Groups = ISNULL(@Groups, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')
    SET @Balance = ISNULL(@Balance, 0)


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @Description = RTRIM(LTRIM(@Description))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Divisions = RTRIM(LTRIM(@Divisions))
    SET @Groups = RTRIM(LTRIM(@Groups))
	SET @Department = RTRIM(LTRIM(@Department))

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Description = @Department
		END
	END
	
	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eTB_ID = ISNULL(AB_Enterprise_Trial_Balance_ID, 0)
		FROM AB_Enterprise_Trial_Balance
		WHERE RTRIM(LTRIM(Account_Number)) = @AccountNo
		  AND RTRIM(LTRIM(Divisions)) = @Divisions
		  AND RTRIM(LTRIM(Groups)) = @Groups

		ORDER BY RTRIM(LTRIM(Account_Number)), RTRIM(LTRIM(Divisions)), RTRIM(LTRIM(Groups)) ASC
	END
	ELSE
	BEGIN
	
		--> SELECT FIRST @Account Name and @Category (in case several exist)
		SELECT TOP 1 @eTB_ID = ISNULL(AB_Enterprise_Trial_Balance_ID, 0)
		FROM AB_Enterprise_Trial_Balance
		WHERE RTRIM(LTRIM([Description])) = @Description
		  AND RTRIM(LTRIM(Divisions)) = @Divisions
		  AND RTRIM(LTRIM(Groups)) = @Groups

		ORDER BY RTRIM(LTRIM([Description])), RTRIM(LTRIM(Divisions)), RTRIM(LTRIM(Groups)) ASC
	END

    IF @eTB_ID IS NULL
        BEGIN
            SET @eTB_ID = 0
        END


    IF @eTB_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Trial_Balance '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Trial_Balance_ID = ' + CONVERT(varchar(20), @eTB_ID)
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Trial_Balance '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Description, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Divisions, '
            SET @sql = @sql + '      Groups, '
            SET @sql = @sql + '      Lup_AB_Account_Departments_ID, '
            SET @sql = @sql + '      Department, '                        
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
        
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           '''' + @Description + '''' + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Divisions + '''' + ', '
            SET @sql = @sql +           '''' + @Groups + '''' + ', '
            SET @sql = @sql +           '' + Convert(Varchar(10),@Lup_AB_Account_Departments_ID) + '' + ', '
            SET @sql = @sql +           '''' + @Department + '''' + ', '                        
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '
        END

   EXEC (@sql)
--Select @Sql
SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Enterprise_Trial_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Enterprise_Trial_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Trial_Balance
--Purpose       :Enterprise Trial Balance Report data
--Functionality :Fetches GL ACCOUNT BALANCE
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @GroupBy and @Grouping sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Trial_Balance]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int        
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(4000),
            @EndPeriod varchar(6)

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

    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [GLAccount], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [GLCategory], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [GLGroup], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '

    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 '
    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 + '         ) '
    SET @sql = @sql + ' ) AS [Balance] '

    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories c '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = c.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Divisions d '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = d.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups e '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = e.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '   

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

    SET @sql = @sql + ' ORDER BY ISNULL(a.Account_Number, '''') ASC '

    EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Enterprise_Trial_Balance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Enterprise_Trial_Balance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Trial_Balance
--Purpose       :Fetch Enterprise Trial Balance
--Date          :2007/08/28
--Authors       :TB
--MODS:         :
--2004.4.8      :05/11/09 - Added @GroupBy and @Grouping sort dimension - RM
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Trial_Balance]
    (
        @GroupBy tinyint,
        @Sort tinyint		
    )

AS

SET NOCOUNT ON


	DECLARE @sql varchar(8000),
            @Grouping varchar(1000)

	Alter Table AB_Enterprise_Trial_Balance
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Trial_Balance
	Drop Column Department


    SET @Grouping = ''

    SET @sql = ' SELECT * '
	SET @sql = @sql + ' FROM AB_Enterprise_Trial_Balance '

    IF @GroupBy = 0
        BEGIN
            SET @Grouping = ' ORDER BY '
        END
    ELSE
    IF @GroupBy = 1
        BEGIN
            SET @Grouping = ' ORDER BY Divisions, '
        END
    ELSE
    IF @GroupBy = 2
        BEGIN
            SET @Grouping = ' ORDER BY Groups, '
        END

    IF @Sort = 0
        BEGIN
            SET @sql = @sql + @Grouping + ' Description '
        END
    ELSE
    IF @Sort = 1
        BEGIN
            SET @sql = @sql + @Grouping + ' Account_Number '
        END
    ELSE
    IF @Sort = 2
        BEGIN
            SET @sql = @sql + @Grouping + ' Category, [Description] '
        END


    EXEC (@sql)

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Enterprise_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Enterprise_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Income_Statement
--Purpose       :SELECT Enterprise Income Statement Report data
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Income_Statement]
    (
        @CompanyID int,
        @MonthID int,
        @YearID 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)


    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)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' b.Sys_AB_I1_ID AS [AB_ID1], '
    SET @sql = @sql + ' b.Sys_AB_I2_ID AS [AB_ID2], '
    SET @sql = @sql + ' b.Sys_AB_I3_ID AS [AB_ID3], '
    SET @sql = @sql + ' b.Sys_AB_I4_ID AS [AB_ID4], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    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 + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
 
    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 + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_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 @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 + '         ) '
            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 + '         ) '
            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, '
    SET @sql = @sql + '          a.Description   '

    EXEC (@sql)

SET NOCOUNT OFF
GO
--Alter AW_Users Table - Add Lup_AP_Product_Bins_ID
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='AW_Users' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AW_Users ADD Lup_AP_Product_Bins_ID Int
GO

UPDATE AW_Users
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AW_Users].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Insert_Enterprise_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Insert_Enterprise_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Income_Statement
--Purpose       :INSERT Enterprise Income Statement Report data
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Income_Statement]
	(
        @ColumnName						varchar(50),
        @Sys_AB_I1_ID					int,
        @Sys_AB_I2_ID					int,
        @Sys_AB_I3_ID					int,
        @Sys_AB_I4_ID					int,
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Level1							varchar(100),
        @Level2							varchar(100),
        @Level3							varchar(100),
        @Level4							varchar(100),
        @Account						varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eIS_ID int,
            @ReturnValue int


    SET @eIS_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Level4 = ISNULL(@Level4, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')
    SET @Balance = ISNULL(@Balance, 0)

    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Level4 = RTRIM(LTRIM(@Level4))
    SET @Account = RTRIM(LTRIM(@Account))
	SET @Department = RTRIM(LTRIM(@Department))    

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END

	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Income_Statement_ID
		FROM AB_Enterprise_Income_Statement
		WHERE Sys_AB_I1_ID = @Sys_AB_I1_ID AND
			  Sys_AB_I2_ID = @Sys_AB_I2_ID AND
			  Sys_AB_I3_ID = @Sys_AB_I3_ID AND
			  Sys_AB_I4_ID = @Sys_AB_I4_ID AND
			  Account_Number = @AccountNo
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END
	ELSE
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Income_Statement_ID
		FROM AB_Enterprise_Income_Statement
		WHERE Sys_AB_I1_ID = @Sys_AB_I1_ID AND
			  Sys_AB_I2_ID = @Sys_AB_I2_ID AND
			  Sys_AB_I3_ID = @Sys_AB_I3_ID AND
			  Sys_AB_I4_ID = @Sys_AB_I4_ID AND
			  Account = @Account
		ORDER BY RTRIM(LTRIM(Account)) ASC
	END


    IF @eIS_ID IS NULL
        BEGIN
            SET @eIS_ID = 0
        END


    IF @eIS_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Income_Statement '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '            
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Income_Statement_ID = ' + CONVERT(varchar(20), @eIS_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Income_Statement '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Sys_AB_I1_ID, '
            SET @sql = @sql + '      Sys_AB_I2_ID, '
            SET @sql = @sql + '      Sys_AB_I3_ID, '
            SET @sql = @sql + '      Sys_AB_I4_ID, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Level4, '
            SET @sql = @sql + '      Account, '
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I1_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I2_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I3_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_I4_ID) + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Level4 + '''' + ', '
            SET @sql = @sql +           '''' + @Account + '''' + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)

RETURN @ReturnValue

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Enterprise_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Enterprise_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Income_Statement
--Purpose       :Fetch Enterprise Income Statement
--Date          :2007/09/05
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Income_Statement]

AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Income_Statement
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Income_Statement
	Drop Column Department


    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Income_Statement '

    SET @sql = @sql + ' ORDER BY Sys_AB_I1_ID, '
    SET @sql = @sql + '          Sys_AB_I2_ID, '
    SET @sql = @sql + '          Sys_AB_I3_ID, '
    SET @sql = @sql + '          Sys_AB_I4_ID, '
    SET @sql = @sql + '          Account   '


    EXEC (@sql)

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Enterprise_Balance_Sheet]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Enterprise_Balance_Sheet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Select_Enterprise_Balance_Sheet
--Purpose       :SELECT Enterprise Balance Sheet Report data
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Balance_Sheet]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

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


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


    SET @sql = ' SELECT '

    SET @sql = @sql + ' a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLAccountID], '
    SET @sql = @sql + ' b.Sys_AB_B1_ID AS [AB_ID1], '
    SET @sql = @sql + ' b.Sys_AB_B2_ID AS [AB_ID2], '
    SET @sql = @sql + ' b.Sys_AB_B3_ID AS [AB_ID3], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [GLAccountNo], '
    SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [GLCategory], '
    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(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '
    
    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) <= ' + '''' + @EndPeriod + ''''
    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_B1 c '
    SET @sql = @sql + '         ON b.Sys_AB_B1_ID = c.Sys_AB_B1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B2 d '
    SET @sql = @sql + '         ON b.Sys_AB_B2_ID = d.Sys_AB_B2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_B3 e '
    SET @sql = @sql + '         ON b.Sys_AB_B3_ID = e.Sys_AB_B3_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '      

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


    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 + '         ) '
            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 + '         ) '
            SET @sql = @sql + ' ) <> 0 '

        END


    SET @sql = @sql + ' ORDER BY b.Sys_AB_B1_ID, '
    SET @sql = @sql + '          b.Sys_AB_B2_ID, '
    SET @sql = @sql + '          b.Sys_AB_B3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '    --Orders the P/L categories
    SET @sql = @sql + '          a.[Description] '

    EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Insert_Enterprise_Balance_Sheet]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Insert_Enterprise_Balance_Sheet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Balance_Sheet
--Purpose       :INSERT Enterprise Balance Sheet Report data
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Balance_Sheet]
	(
        @ColumnName						varchar(50),
        @Sys_AB_B1_ID					int,
        @Sys_AB_B2_ID					int,
        @Sys_AB_B3_ID					int,
        @AccountNo						varchar(16),
        @Category						varchar(100),
        @Level1							varchar(100),
        @Level2							varchar(100),
        @Level3							varchar(100),
        @Account						varchar(50),
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        @Balance						money,
        @GroupByDepartment				tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eIS_ID int,
            @ReturnValue int


    SET @eIS_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Category = ISNULL(@Category, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')   
    SET @Balance = ISNULL(@Balance, 0)


    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Category = RTRIM(LTRIM(@Category))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Account = RTRIM(LTRIM(@Account))
	SET @Department = RTRIM(LTRIM(@Department))        

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END

	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Balance_Sheet_ID
		FROM AB_Enterprise_Balance_Sheet
		WHERE Sys_AB_B1_ID = @Sys_AB_B1_ID AND
			  Sys_AB_B2_ID = @Sys_AB_B2_ID AND
			  Sys_AB_B3_ID = @Sys_AB_B3_ID AND
			  Account_Number = @AccountNo
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END
	ELSE
	BEGIN
		--> SELECT FIRST @AccountNo and @Category (in case several exist)
		SELECT TOP 1 @eIS_ID = AB_Enterprise_Balance_Sheet_ID
		FROM AB_Enterprise_Balance_Sheet
		WHERE Sys_AB_B1_ID = @Sys_AB_B1_ID AND
			  Sys_AB_B2_ID = @Sys_AB_B2_ID AND
			  Sys_AB_B3_ID = @Sys_AB_B3_ID AND
			  Account = @Account
		ORDER BY RTRIM(LTRIM(Account_Number)) ASC
	END

    IF @eIS_ID IS NULL
        BEGIN
            SET @eIS_ID = 0
        END


    IF @eIS_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Balance_Sheet '
            SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '            
            SET @sql = @sql + '      Total = ISNULL(Total, 0) + ' + CONVERT(varchar(50), @Balance)
            SET @sql = @sql + '  WHERE AB_Enterprise_Balance_Sheet_ID = ' + CONVERT(varchar(20), @eIS_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Balance_Sheet '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      Sys_AB_B1_ID, '
            SET @sql = @sql + '      Sys_AB_B2_ID, '
            SET @sql = @sql + '      Sys_AB_B3_ID, '
            SET @sql = @sql + '      Account_Number, '
            SET @sql = @sql + '      Category, '
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Account, '
            SET @sql = @sql + '      Total, '
            SET @sql = @sql +        @ColumnName + ' '
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B1_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B2_ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @Sys_AB_B3_ID) + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '
            SET @sql = @sql +           '''' + @Category + '''' + ', '
            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Account + '''' + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ', '
            SET @sql = @sql +           CONVERT(varchar(50), @Balance) + ' '
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)

RETURN @ReturnValue

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Enterprise_Balance_Sheet]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Enterprise_Balance_Sheet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Balance_Sheet
--Purpose       :Fetch Enterprise Income Statement
--Date          :2007/09/09
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Balance_Sheet]

AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Balance_Sheet
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Balance_Sheet
	Drop Column Department

    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Balance_Sheet '

    SET @sql = @sql + ' ORDER BY Sys_AB_B1_ID, '
    SET @sql = @sql + '          Sys_AB_B2_ID, '
    SET @sql = @sql + '          Sys_AB_B3_ID, '
    SET @sql = @sql + '          Account   '


    EXEC (@sql)

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Enterprise_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Enterprise_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Enterprise_Management_Accounts
--Purpose       :Fetch Enterprise Management Accounts
--Date          :2007/09/22
--Authors       :TB
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_Enterprise_Management_Accounts]
(
	@CombineSalesCOS tinyint
)
AS

SET NOCOUNT ON


	DECLARE @sql varchar(4000)

	Alter Table AB_Enterprise_Management_Accounts
	Drop Column Lup_AB_Account_Departments_ID

	Alter Table AB_Enterprise_Management_Accounts
	Drop Column Department

    SET @sql = ' SELECT * '
    SET @sql = @sql + ' FROM AB_Enterprise_Management_Accounts '

    --SET @sql = @sql + ' ORDER BY IS1ID, '
    --SET @sql = @sql + '          IS2ID, '
    --SET @sql = @sql + '          IS3ID, '
    --SET @sql = @sql + '          IS4ID, '
    --SET @sql = @sql + '          Account   '


    SET @sql = @sql + ' ORDER BY IS1ID, '
    SET @sql = @sql + '          IS2ID, '
    SET @sql = @sql + '          IS3ID, '
--    SET @sql = @sql + '          [Level4], '
 --   SET @sql = @sql + '          Account,   '


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

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          IS4ID, '
        END

    SET @sql = @sql + '          GLDivision, '
    SET @sql = @sql + '          GLGroup, '

    IF @CombineSalesCOS = 1
        BEGIN
            ------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          IS4ID, '
            ------------------------------------------------------------

            SET @sql = @sql + '          AccountNo, '
        END

    SET @sql = @sql + '          Account   '




    EXEC (@sql)



SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Select_Enterprise_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Select_Enterprise_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Management_Account_Groups
--Purpose       :SELECT Enterprise Management Accounts Report data. Based on sp_RPT_AB_Management_Account_Groups
--Parameters    :
--Date          :2015/08/20
--Authors       :RL
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AB_Select_Enterprise_Management_Accounts]
    (
        @CompanyID int,
        @MonthID int,
        @YearID int,
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint,
        @CombineSalesCOS tinyint
    )

AS

SET NOCOUNT ON

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

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


    ------------------------------------------------
    -- Get the DESCRIPTION of the Revenue Category
    ------------------------------------------------
    SELECT @RevenueCategory = Description
    FROM Sys_AB_Account_Categories
    WHERE Sys_AB_Account_Categories_ID = 13
    ------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' b.Sys_AB_I1_ID AS [IS1ID], '
    SET @sql = @sql + ' b.Sys_AB_I2_ID AS [IS2ID], '
    SET @sql = @sql + ' b.Sys_AB_I3_ID AS [IS3ID], '
    SET @sql = @sql + ' b.Sys_AB_I4_ID AS [IS4ID], '
    SET @sql = @sql + ' a.AB_Accounts_ID AS [GLID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Divisions_ID AS [DivisionID], '
    SET @sql = @sql + ' a.Lup_AB_Account_Groups_ID AS [GroupID], '
    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + ' CASE WHEN b.Sys_AB_Account_Categories_ID = 14 '
            SET @sql = @sql + '      THEN ''' + @RevenueCategory + ''' '
            SET @sql = @sql + '      ELSE ISNULL(b.[Description], '''') '
            SET @sql = @sql + ' END AS [Level4], ' 
        END
    ELSE
         BEGIN
            SET @sql = @sql + ' ISNULL(b.[Description], '''') AS [Level4], '
         END

    SET @sql = @sql + ' ISNULL(g.[Description], '''') AS [GLDivision], '
    SET @sql = @sql + ' ISNULL(h.[Description], '''') AS [GLGroup], '
    SET @sql = @sql + ' ISNULL(a.Account_Number, '''') AS [AccountNo], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '
    SET @sql = @sql + ' ISNULL(a.[Lup_AB_Account_Departments_ID], '''') AS [Lup_AB_Account_Departments_ID], '
    SET @sql = @sql + ' ISNULL(r.[Description], 1) AS [Department], '

    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), @MonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)

    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Actual], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
    SET @sql = @sql + '           Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID)
    SET @sql = @sql + ' ) AS [Budget], '


    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 + ''''
    
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [YTDActual], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(Budget_Amount), 0) '
    SET @sql = @sql + '     FROM AB_Budgets '
    SET @sql = @sql + '     WHERE AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(Slu_AW_Months_ID, Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
    SET @sql = @sql + ' ) AS [YTDBudget] '




    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 + '     LEFT JOIN Lup_AB_Account_Divisions g '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Divisions_ID = g.Lup_AB_Account_Divisions_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Groups h '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Groups_ID = h.Lup_AB_Account_Groups_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AB_Account_Departments r '
    SET @sql = @sql + '         ON a.Lup_AB_Account_Departments_ID = r.Lup_AB_Account_Departments_ID '         

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '   AND 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 + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            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 + '         ) '
            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 + '         ) '
--             SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            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 + '         ) '
            SET @sql = @sql + ' ) <> 0 '

            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) >= ' + '''' + @StartPeriod + ''''
            SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''

            IF @IgnoreYEJnl = 1
                BEGIN
                    SET @sql = @sql + '          AND Sys_AB_Transaction_Types_ID <> 16'
                END
            SET @sql = @sql + '         ) '
            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, '

    IF @CombineSalesCOS = 1
        BEGIN
            SET @sql = @sql + '          [Level4], '
        END
    ELSE
        BEGIN
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
        END

    SET @sql = @sql + '          g.[Description], '
    SET @sql = @sql + '          h.[Description], '

    IF @CombineSalesCOS = 1
        BEGIN
            --------------------------------------------------------------
            --> 2004.4.4 - Added this line to DISPLAY SALES ACCOUNTS FIRST
            SET @sql = @sql + '          b.Sys_AB_I4_ID, '
            --------------------------------------------------------------

            SET @sql = @sql + '          a.Account_Number, '
        END

    SET @sql = @sql + '          a.Description   '


EXEC (@sql)

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Insert_Enterprise_Management_Accounts]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Insert_Enterprise_Management_Accounts]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Enterprise_Management_Accounts
--Purpose       :INSERT Enterprise Management Accounts Report data
--Date          :2015-08-20
--Authors       :RL
--MODS:         :
--RL	V6.2	:2016-06-24 - Added Account Department Grouping
-----------------------	--------------------------------------------------------

CREATE PROCEDURE [sp_AB_Insert_Enterprise_Management_Accounts]
	(
        @ColumnName varchar(50),
       	@IS1ID [int],
       	@IS2ID [int],
       	@IS3ID [int],       	       	
       	@IS4ID [int],
       	
       	@GLID [int],
       	@DivisionID int,
        @GroupID int,
        
        @Level1 varchar(100),
        @Level2 varchar(100),
        @Level3 varchar(100),
        @Level4 varchar(100),
        
        @GLDivision varchar(100),
        @GLGroup varchar(100),
        @AccountNo varchar(100),
        @Account varchar(100),
        
		@Lup_AB_Account_Departments_ID	int,
		@Department						varchar(50),
        
        @Actual money,
        @Budget money,
        @YTDActual money,
        @YTDBudget money,
        @GroupByDepartment				tinyint                
  	)
AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000),
            @eMA_ID int,
            @ReturnValue int

    SET @eMA_ID = 0
    SET @ReturnValue = 0


    SET @ColumnName = ISNULL(@ColumnName, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Level1 = ISNULL(@Level1, '')
    SET @Level2 = ISNULL(@Level2, '')
    SET @Level3 = ISNULL(@Level3, '')
    SET @Level4 = ISNULL(@Level4, '')
    SET @GLDivision = ISNULL(@GLDivision, '')
    SET @GLGroup = ISNULL(@GLGroup, '')
    SET @AccountNo = ISNULL(@AccountNo, '')
    SET @Account = ISNULL(@Account, '')
    SET @Lup_AB_Account_Departments_ID = ISNULL(@Lup_AB_Account_Departments_ID, 1)
    SET @Department = ISNULL(@Department, '')   
    SET @Actual = ISNULL(@Actual, 0)
    SET @Budget = ISNULL(@Budget, 0)
    SET @YTDActual = ISNULL(@YTDActual, 0)
    SET @YTDBudget = ISNULL(@YTDBudget, 0)

    
    SET @ColumnName = RTRIM(LTRIM(@ColumnName))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Level1 = RTRIM(LTRIM(@Level1))
    SET @Level2 = RTRIM(LTRIM(@Level2))
    SET @Level3 = RTRIM(LTRIM(@Level3))
    SET @Level4 = RTRIM(LTRIM(@Level4))
    SET @GLDivision = RTRIM(LTRIM(@GLDivision))
    SET @GLGroup = RTRIM(LTRIM(@GLGroup))
    SET @AccountNo = RTRIM(LTRIM(@AccountNo))
    SET @Department = RTRIM(LTRIM(@Department))        

    --> SELECT FIRST @AccountNo and @Category (in case several exist)
    --SELECT TOP 1 @eIS_ID = AB_Enterprise_Management_Accounts_ID
    --FROM AB_Enterprise_Management_Accounts
    --WHERE Level1 = @Level1 AND
    --      Level2 = @Level2 AND
    --      Level3 = @Level3 AND
    --      Level4 = @Level4 AND
    --      AccountNo = @AccountNo
    --ORDER BY RTRIM(LTRIM(AccountNo)) ASC

	IF @GroupByDepartment = 1
	BEGIN
		IF @Lup_AB_Account_Departments_ID <> 1
		BEGIN
			SET @Account = @Department
		END
	END


	--RL	V6.2	Added Account Departments
	--If grouping by account department is selected then Account name is used and not account number
	IF @GroupByDepartment = 0
	BEGIN
		SELECT TOP 1 @eMA_ID = ISNULL(AB_Enterprise_Management_Accounts_ID, 0)
		FROM AB_Enterprise_Management_Accounts
		WHERE RTRIM(LTRIM(AccountNo)) = @AccountNo
		  AND RTRIM(LTRIM(GLDivision)) = @GLDivision
		  AND RTRIM(LTRIM(GLGroup)) = @GLGroup

		ORDER BY RTRIM(LTRIM(AccountNo)), RTRIM(LTRIM(GLDivision)), RTRIM(LTRIM(GLGroup)) ASC
	END
	ELSE
	BEGIN
		SELECT TOP 1 @eMA_ID = ISNULL(AB_Enterprise_Management_Accounts_ID, 0)
		FROM AB_Enterprise_Management_Accounts
		WHERE RTRIM(LTRIM(Account)) = @Account
		  AND RTRIM(LTRIM(GLDivision)) = @GLDivision
		  AND RTRIM(LTRIM(GLGroup)) = @GLGroup

		ORDER BY RTRIM(LTRIM(Account)), RTRIM(LTRIM(GLDivision)), RTRIM(LTRIM(GLGroup)) ASC
	END


    IF @eMA_ID IS NULL
    BEGIN
		SET @eMA_ID = 0
    END


    IF @eMA_ID > 0
        BEGIN
            SET @sql = '  UPDATE AB_Enterprise_Management_Accounts '
            
            --SET @sql = @sql + '  SET ' + @ColumnName + ' = ISNULL( ' + @ColumnName + ',0) + ' + CONVERT(varchar(50), @Balance) + ', '                        
            
            SET @sql = @sql + '  SET ' + @ColumnName + '_Act = ISNULL( ' + @ColumnName + '_Act,0) + ' + CONVERT(varchar(50), @Actual) + ', '  
            --SET @sql = @sql + '  SET ' + @ColumnName + '_Act = ' + CONVERT(varchar(50), @Actual) + ', '            
            SET @sql = @sql + '      TotalActual = ISNULL(TotalActual, 0) + ' + CONVERT(varchar(50), @Actual) + ', '

			SET @sql = @sql + '   ' + @ColumnName + '_Bud = ISNULL( ' + @ColumnName + '_Bud,0) + ' + CONVERT(varchar(50), @Budget) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_Bud = ' + CONVERT(varchar(50), @Budget) + ', '
            SET @sql = @sql + '      TotalBudget = ISNULL(TotalBudget, 0) + ' + CONVERT(varchar(50), @Budget) + ', '

			SET @sql = @sql + '   ' + @ColumnName + '_YTDAct = ISNULL( ' + @ColumnName + '_YTDAct,0) + ' + CONVERT(varchar(50), @YTDActual) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_YTDAct = ' + CONVERT(varchar(50), @YTDActual) + ', '
            SET @sql = @sql + '      TotalYTDActual = ISNULL(TotalYTDActual, 0) + ' + CONVERT(varchar(50), @YTDActual) + ', '            

			SET @sql = @sql + '   ' + @ColumnName + '_YTDBud = ISNULL( ' + @ColumnName + '_YTDBud,0) + ' + CONVERT(varchar(50), @YTDBudget) + ', '  
            --SET @sql = @sql + '   ' + @ColumnName + '_YTDBud = ' + CONVERT(varchar(50), @YTDBudget) + ', '
            SET @sql = @sql + '      TotalYTDBudget = ISNULL(TotalYTDBudget, 0) + ' + CONVERT(varchar(50), @YTDBudget) + ' '
            
            SET @sql = @sql + '  WHERE AB_Enterprise_Management_Accounts_ID = ' + CONVERT(varchar(20), @eMA_ID)

            SET @ReturnValue = 1
        END

    ELSE
        BEGIN
            SET @sql = '  INSERT AB_Enterprise_Management_Accounts '
            SET @sql = @sql + '  ( '
            SET @sql = @sql + '      IS1ID, '
            SET @sql = @sql + '      IS2ID, '
            SET @sql = @sql + '      IS3ID, '                                    
            SET @sql = @sql + '      IS4ID, '
            
            SET @sql = @sql + '      GLID, '
            SET @sql = @sql + '      DivisionID, '
            SET @sql = @sql + '      GroupID, '
            
            SET @sql = @sql + '      Level1, '
            SET @sql = @sql + '      Level2, '
            SET @sql = @sql + '      Level3, '
            SET @sql = @sql + '      Level4, '
            
            SET @sql = @sql + '      GLDivision, '
            SET @sql = @sql + '      GLGroup, '
            SET @sql = @sql + '      AccountNo, '
            SET @sql = @sql + '      Account, '
            
            SET @sql = @sql + '      TotalActual, '
            SET @sql = @sql + '      TotalBudget, '
            SET @sql = @sql + '      TotalYTDActual, '
            SET @sql = @sql + '      TotalYTDBudget, '
                       
            SET @sql = @sql +        @ColumnName + '_Act, '
			SET @sql = @sql +        @ColumnName + '_Bud, '
			SET @sql = @sql +        @ColumnName + '_YTDAct, '						
			SET @sql = @sql +        @ColumnName + '_YTDBud '			
            SET @sql = @sql + '  ) '
            SET @sql = @sql + '  VALUES '
            SET @sql = @sql + '  ( '
            SET @sql = @sql +           CONVERT(varchar(20), @IS1ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS2ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS3ID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @IS4ID) + ', '                                    
            SET @sql = @sql +           CONVERT(varchar(20), @GLID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @DivisionID) + ', '
            SET @sql = @sql +           CONVERT(varchar(20), @GroupID) + ', '

            SET @sql = @sql +           '''' + @Level1 + '''' + ', '
            SET @sql = @sql +           '''' + @Level2 + '''' + ', '
            SET @sql = @sql +           '''' + @Level3 + '''' + ', '
            SET @sql = @sql +           '''' + @Level4 + '''' + ', '

            SET @sql = @sql +           '''' + @GLDivision + '''' + ', '
            SET @sql = @sql +           '''' + @GLGroup + '''' + ', '
            SET @sql = @sql +           '''' + @AccountNo + '''' + ', '            
            SET @sql = @sql +           '''' + @Account + '''' + ', '


            SET @sql = @sql +           CONVERT(varchar(50), @Actual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @Budget) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDActual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDBudget) + ', '			
			
            SET @sql = @sql +           CONVERT(varchar(50), @Actual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @Budget) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDActual) + ', '
			SET @sql = @sql +           CONVERT(varchar(50), @YTDBudget) + ' '			
            SET @sql = @sql + '  ) '

            SET @ReturnValue = 2
        END


    EXEC (@sql)
--Select @sql
RETURN @ReturnValue

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Bin_Allocation_History]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Bin_Allocation_History]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Bin_Allocation_History
--Purpose       :Returns Bin Allocation History
--Date          :2016-07-27
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Bin_Allocation_History]
    (
        @FromBin_ID			int,
        @ToBin_ID			int,        
        @FromDate			datetime,
        @ToDate				datetime,
        @CompanyID			int
    )
AS

SET NOCOUNT ON

IF ( (@FromBin_ID = 0) AND (@ToBin_ID = 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
END

IF ( (@FromBin_ID <> 0) AND (@ToBin_ID <> 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.From_Lup_AP_Product_Bins_ID = @FromBin_ID
	AND h.To_Lup_AP_Product_Bins_ID = @ToBin_ID
END

IF ( (@FromBin_ID = 0) AND (@ToBin_ID <> 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.To_Lup_AP_Product_Bins_ID = @ToBin_ID	
END

IF ( (@FromBin_ID <> 0) AND (@ToBin_ID = 0) )
BEGIN
	SELECT	h.Batch_No, h.Date_Captured, 
			p.Product_Code,	p.[Description] AS [Product],
			f.[Description] AS [From Bin], h.From_Bin_Previous_On_Hand, h.From_Bin_New_On_Hand,
			t.[Description] AS [To Bin], h.To_Bin_Previous_On_Hand, h.To_Bin_New_On_Hand,
			ABS(h.From_Bin_Previous_On_Hand - h.From_Bin_New_On_Hand) AS [Transfer Qty],
			ISNULL(FirstName,'') + ' ' + ISNULL(Surname,'') As [User]
	FROM AP_Products_Bins_History h
		INNER JOIN Lup_AP_Product_Bins f
			ON h.From_Lup_AP_Product_Bins_ID = f.Lup_AP_Product_Bins_ID
		INNER JOIN Lup_AP_Product_Bins t
			ON h.To_Lup_AP_Product_Bins_ID = t.Lup_AP_Product_Bins_ID
		INNER JOIN AP_Products p
			ON h.AP_Products_ID = p.AP_Products_ID		
		INNER JOIN AW_Users u
			ON h.[User_ID] = u.AW_Users_ID
	WHERE Batch_No <> 0
	AND h.Date_Captured BETWEEN @FromDate AND @ToDate
	AND h.From_Lup_AP_Product_Bins_ID = @FromBin_ID	
END
GO
--Insert Product Bin Allocation
IF NOT EXISTS
(
	SELECT Sys_AW_Reports_ID
	FROM Sys_AW_Reports
	WHERE Report_No = '225' 
	AND	Method_Name = 'Show_BinAllocations'
) 

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
	(
		2,
		0,
		'Product Reports',
		'225',
		'Bin Allocations History',
		'Bin Allocations History',
		'SpSProductReports',
		'CInterface',
		'Show_BinAllocations'
	)
END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Product_Bin_Qty]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Product_Bin_Qty]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Product_Bin_Qty
--Purpose       :Returns stock quantity in a Bin
--Parameters    :
--Date          :2015-11-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Product_Bin_Qty]
	(
        @ProductID					int,
        @Lup_AP_Product_Bins_ID		int,
        @AW_User_Companies_ID		int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)
		SET @Qty = 0
		
            SELECT @Qty = ISNULL(On_Hand, 0)
            FROM AP_Products_Bins
            WHERE AP_Products_ID = @ProductID AND
				  Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID AND
				  AW_User_Companies_ID = @AW_User_Companies_ID

    	RETURN @Qty
    END
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AC_Product_Bins]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN


	CREATE TABLE [AC_Product_Bins]
	(
		[AC_Product_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] 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_AC_Product_Bins] PRIMARY KEY CLUSTERED 
		(
			[AC_Product_Bins_ID] ASC
		)
	)
END
GO

EXEC dbo.sp_bindefault @defname=N'[dbo].[df_Date_Captured]', @objname=N'[dbo].[AC_Product_Bins].[Date_Captured]'
GO

EXEC dbo.sp_bindefault @defname=N'[dbo].[df_User_ID]', @objname=N'[dbo].[AC_Product_Bins].[User_ID]'
GO

EXEC dbo.sp_bindefault @defname=N'[dbo].[df_User_Companies]', @objname=N'[dbo].[AC_Product_Bins].[AW_User_Companies_ID]'
GO

EXEC dbo.sp_bindefault @defname=N'[dbo].[df_Active]', @objname=N'[dbo].[AC_Product_Bins].[Slu_AW_Active_ID]'
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'AC_Product_Bins_AC_Customers_ID'
)
DROP INDEX AC_Product_Bins.AC_Product_Bins_AC_Customers_ID
GO
CREATE INDEX AC_Product_Bins_AC_Customers_ID
   ON AC_Product_Bins (AC_Customers_ID)
	WITH FILLFACTOR = 80
GO
--Insert Journal - Bad Debt Transaction Types
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Journal/Bad Debt'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Journal/Bad Debt',
		'SJJNB',
		0,
		1,
		1
	)
END
GO
--Alter AP_Stock_Transfer_Details Table - Add Lup_AP_Product_Bins_ID
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_Stock_Transfer_Details' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AP_Stock_Transfer_Details ADD Lup_AP_Product_Bins_ID Integer
GO

UPDATE AP_Stock_Transfer_Details
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Stock_Transfer_Details].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO
--Alter AP_Stock_Transfer_Log Table - Add Lup_AP_Product_Bins_ID
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_Stock_Transfer_Log' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AP_Stock_Transfer_Log ADD Lup_AP_Product_Bins_ID Integer
GO

UPDATE AP_Stock_Transfer_Log
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Stock_Transfer_Log].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_Reserved_Bin
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product per Bin
--Parameters    :
--Date          :2017-05-15
--Authors       :RL
--MODS          :
--V6.3	RL	2017-04-21	:Added Back order amount for Sales Orders
--V6.3	RL	2017-05-15	:Added Bin Check
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_Reserved_Bin]
    (
        @ProductID	int,
        @BinID		int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity + d.Back_Order), 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
              d.Lup_AP_Product_Bins_ID = @BinID AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

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

--Insert chkSOPromtBOAdd - Used on POS
--chkSOPromtBOAdd
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOPromtBOJobCard'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOPromtBOJobCard',
		0,
		'0',
		Getdate(),
		1,
		1
	)
END
GO

--Insert chkSOPromtBOAdd - Used on POS
--chkSOPromtBOAdd
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOPromtBOInvoice'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOPromtBOInvoice',
		0,
		'0',
		Getdate(),
		1,
		1
	)
END
GO

--Insert chkSOPromtBOAdd - Used on POS
--chkSOPromtBOAdd
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOPromtBOProforma'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOPromtBOProforma',
		0,
		'0',
		Getdate(),
		1,
		1
	)
END
GO
--Insert chkSOPromtBOAdd - Used on POS
--chkSOPromtBOAdd
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOPromtBOSalesOrder'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOPromtBOSalesOrder',
		0,
		'1',
		Getdate(),
		1,
		1
	)
END
GO

--Insert chkSOPromtBOAdd - Used on POS
--chkSOPromtBOAdd
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOPromtBOConsignment'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOPromtBOConsignment',
		0,
		'0',
		Getdate(),
		1,
		1
	)
END
GO
--Insert chkSOAutoAddPO - Used on POS
--chkSOAutoAddPO
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOAutoAddPO'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOAutoAddPO',
		0,
		'1',
		Getdate(),
		1,
		1
	)
END
GO
--Insert chkSOAutoReplenishBO_GRV - Automaticaly replenish BO when doing GRV's
--chkSOAutoReplenishBO_GRV
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSOAutoReplenishBO_GRV'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSOAutoReplenishBO_GRV',
		0,
		'1',
		Getdate(),
		1,
		1
	)
END
GO


--Insert chkPOSSalespersonAsSalesRep - Defaults Sales Rep to customer Salesperson
--chkPOSSalespersonAsSalesRep
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkPOSSalespersonAsSalesRep'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkPOSSalespersonAsSalesRep',
		0,
		'0',
		Getdate(),
		1,
		1
	)
END
GO

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

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

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

UPDATE Sys_AW_Options
SET Control_Value = 0
WHERE Control_Name = 'chkDisableSourceSO'
GO

IF EXISTS
(
	SELECT 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkDisableSourceJob'
	AND Control_Value = '1'
)
BEGIN
	UPDATE Sys_AW_Options
	SET Control_Value = '1'
	WHERE Control_Name = 'chkDisableSourceSO'
END
ELSE
BEGIN
	UPDATE Sys_AW_Options
	SET Control_Value = '0'
	WHERE Control_Name = 'chkDisableSourceSO'
END
GO

--1. Modify AW_Users table as follows
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='AW_Users' AND
        C.Name='IsTillPayout'
) 
BEGIN
  ALTER TABLE AW_Users ADD IsTillPayout tinyint
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Users].[IsTillPayout]'
  -------------------------------------------------------
END
GO

UPDATE AW_Users
SET IsTillPayout = 0
Go

UPDATE AW_Users
SET IsTillPayout = 1
WHERE IsSupervisor = 1
Go
--Alter AO_GRV Table - Add Notes for Sales Order Replenishment
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='AO_GRV' AND
        C.Name='Notes'
) 
ALTER TABLE AO_GRV ADD Notes Varchar(500)
GO

UPDATE AO_GRV
SET Notes = ''
Where ISNULL(Notes,'') = ''
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV].[Notes]'
-------------------------------------------------------
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AW_Exists_SO_Customer_Reference]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AW_Exists_SO_Customer_Reference]
GO
-------------------------------------------------------------------------------
--Description   :dbo.fn_AW_Exists_SO_Customer_Reference
--Purpose       :Returns FLAG if AS_Transactions.Customer_Reference exists for an active sales order
--Date          :2017/09/27 V6.3
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AW_Exists_SO_Customer_Reference]
	(
        @Value varchar(1000),
        @ActorID int,
        @CompanyID int
	)

RETURNS bit

AS

    BEGIN
    
    	DECLARE @Test bit

        IF EXISTS
            (
                SELECT TOP 1 AS_Transactions_ID
                FROM AS_Transactions
                WHERE AC_Customers_ID = @ActorID AND 
					  ISNULL(Customer_Reference,'') = @Value AND
                      AW_User_Companies_ID = @CompanyID AND
                      Sys_AW_Transaction_Types_ID = 16 AND
					  Slu_AW_Active_ID = 1
            )

    		SET @Test = 1
    	ELSE	
    		SET @Test = 0

    	RETURN @Test

    END
GO
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
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [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],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
GO
--Alter AS_Transactions Table - Change Version_Number From smallint to integer
--Used for Sales Order Updates
IF EXISTS
(
	SELECT * 
	  FROM SysObjects O 
	  INNER JOIN SysColumns C
		ON O.ID = C.ID
	  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
			O.Name='AS_Transactions' AND
			C.Name='Version_Number' AND
			C.cdefault <> 0
)
EXEC sp_unbindefault '[AS_Transactions].[Version_Number]'
GO
ALTER TABLE AS_Transactions Alter Column Version_Number Int
GO
------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'
-------------------------------------------------------
GO
--Add AS_Transactions_ID
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_Sales_Order_Details' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AS_Sales_Order_Details ADD Lup_AP_Product_Bins_ID int
GO

EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_One]', @objname = N'[dbo].[AS_Sales_Order_Details].[Lup_AP_Product_Bins_ID]'
GO

UPDATE AS_Sales_Order_Details
SET Lup_AP_Product_Bins_ID = 1
Where Lup_AP_Product_Bins_ID IS NULL
GO

--Add Order Number
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_Sales_Order_Details' AND
        C.Name='Customer_Reference'
) 
ALTER TABLE AS_Sales_Order_Details ADD Customer_Reference varchar(15)
GO

EXECUTE sp_bindefault @defname = N'[dbo].[df_Nullstring]', @objname = N'[dbo].[AS_Sales_Order_Details].[Customer_Reference]'
GO

UPDATE AS_Sales_Order_Details
SET Customer_Reference = ''
Where Customer_Reference IS NULL
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_Reserved]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_SUM_Product_Job_Reserved]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_Reserved
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product
--Parameters    :
--Date          :2006/12/13
--Authors       :TB
--MODS          :
--V6.3	RL	2017-04-21	:Added Back order amount for Sales Orders
----------------------------------------------------------------------------

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

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        SELECT @ReservedQTY = ISNULL(SUM(d.Quantity + d.Back_Order), 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 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Products_Sales_Order_Reserved]')
	AND xtype 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          :
----V6.3	RL	2017-05-04	:Added Back Order Qty on Sales Orders
----------------------------------------------------------------------------

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 + d.Back_Order), 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
--Alter AW_Users Table - Changed Default IsRecordsManager to No
IF EXISTS
(
	SELECT * 
	  FROM SysObjects O 
	  INNER JOIN SysColumns C
		ON O.ID = C.ID
	  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
			O.Name='AW_Users' AND
			C.Name='IsRecordsManager' AND
			C.cdefault <> 0
)
EXEC sp_unbindefault '[AW_Users].[IsRecordsManager]'
GO
------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Users].[IsRecordsManager]'
-------------------------------------------------------
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_SO_Reserved_NO_BO]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_NO_BO]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_SO_Reserved_NO_BO
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product excluding back orders
--Parameters    :
--Date          :2017/10/10
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

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

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        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 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO
--Purpose       :SUM all JOB CARD and SALES ORDER RESERVED for one Product excluding back orders
--Parameters    :
--Date          :2017/10/10
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_SUM_Product_Job_SO_Reserved_Bin_NO_BO]
    (
        @ProductID	int,
        @BinID		int
    )

RETURNS float

AS

    BEGIN

        DECLARE @ReservedQTY float

    -------------------------------------------------------------------------------
    -- JOB CARD and SALES ORDER RESERVED
    -------------------------------------------------------------------------------
        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
              d.Lup_AP_Product_Bins_ID = @BinID AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
              
    -------------------------------------------------------------------------------


        RETURN(@ReservedQTY)

    
    END
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AB_GL_Transactions_Audit]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN
	CREATE TABLE AB_GL_Transactions_Audit
	(
		AB_GL_Transactions_Audit_ID	int IDENTITY(1,1) NOT NULL,
		Record_Action				varchar(50) NULL,
		AB_GL_Transactions_ID		int NULL,
		Field						varchar(50) NULL,
		Prev_Value					varchar(50) NULL,
		New_Value					varchar(50) NULL,
		Date_Captured				datetime NULL,
		[User_ID]					int NULL,
		 CONSTRAINT [PK_AB_GL_Transactions_Audit_ID] PRIMARY KEY CLUSTERED 
		(
			AB_GL_Transactions_Audit_ID ASC
		)
	)
END

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

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

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

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

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

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

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

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

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
--V5.6.0	RL	:2014-04-10 - Added Sell Below Cost
--V5.6.2	RL	:2015-12-01 - Added Consignment stock quantity
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
-------------------------------------------------------------------------------
--NB NB NB - NO SPECIFIC COMPANY IS SELECTED - done from where view is called
-------------------------------------------------------------------------------

CREATE VIEW [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],
        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock]
	FROM AP_Products p  
		LEFT JOIN Sys_AW_Tax_Codes tc
            ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
GO
--Alter AP_Products_Stock_Takes Table - Add Lup_AP_Product_Bins_ID
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_Stock_Takes' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AP_Products_Stock_Takes ADD Lup_AP_Product_Bins_ID Integer
GO

UPDATE AP_Products_Stock_Takes
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Stock_Takes].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO

--Alter AP_Products_Stock_Takes Table - Add Total_On_Hand
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_Stock_Takes' AND
        C.Name='Total_On_Hand'
) 
ALTER TABLE AP_Products_Stock_Takes ADD Total_On_Hand Decimal(9,3)
GO

UPDATE AP_Products_Stock_Takes
SET Total_On_Hand = 0
Where ISNULL(Total_On_Hand,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Total_On_Hand]'
-------------------------------------------------------
GO


--Alter AP_Products_Stock_Takes Table - Add Consignment_Qty
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_Stock_Takes' AND
        C.Name='Consignment_Qty'
) 
ALTER TABLE AP_Products_Stock_Takes ADD Consignment_Qty Decimal(9,3)
GO

UPDATE AP_Products_Stock_Takes
SET Consignment_Qty = 0
Where ISNULL(Consignment_Qty,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Consignment_Qty]'
-------------------------------------------------------
GO

--Alter AP_Products_Stock_Takes Table - Add On_Hand_Calc
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_Stock_Takes' AND
        C.Name='On_Hand_Calc'
) 
ALTER TABLE AP_Products_Stock_Takes ADD On_Hand_Calc Decimal(9,3)
GO

UPDATE AP_Products_Stock_Takes
SET On_Hand_Calc = 0
Where ISNULL(On_Hand_Calc,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[On_Hand_Calc]'
-------------------------------------------------------
GO

--Alter AP_Products_Stock_Takes Table - Add Variance_Calc
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_Stock_Takes' AND
        C.Name='Variance_Calc'
) 
ALTER TABLE AP_Products_Stock_Takes ADD Variance_Calc Decimal(9,3)
GO

UPDATE AP_Products_Stock_Takes
SET Variance_Calc = 0
Where ISNULL(Variance_Calc,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Variance_Calc]'
-------------------------------------------------------
GO
--1. Modify AW_Users table as follows
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='AW_Users' AND
        C.Name='IsBinSuper'
) 
BEGIN
  ALTER TABLE AW_Users ADD IsBinSuper tinyint
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Users].[IsBinSuper]'
  -------------------------------------------------------
END
GO

UPDATE AW_Users
SET IsBinSuper = 0
WHERE ISNULL(IsBinSuper,0) = 0
Go
IF EXISTS
( 
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Product_Bin_Job_Reserved]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Product_Bin_Job_Reserved]
GO
----------------------------------------------------------------------------
--Description   :fn_AP_Get_Product_Bin_Job_Reserved
--Purpose       :SUM all JOB CARD for one Product and Bin
--Parameters    :
--Date          :2015/05/09
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

CREATE FUNCTION [fn_AP_Get_Product_Bin_Job_Reserved]
    (
        @ProductID		int,
        @ProductBinID	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 ISNULL(Lup_AP_Product_Bins_ID,0) = @ProductBinID
		AND (h.Sys_AW_Transaction_Types_ID = 2)
              
	RETURN(@ReservedQTY)
   
END
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[Lup_AB_Account_Departments]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN

	CREATE TABLE [Lup_AB_Account_Departments]
	(
		[Lup_AB_Account_Departments_ID] [int] IDENTITY(1,1) NOT NULL,
		[Description] [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_Lup_AB_Account_Departments] PRIMARY KEY CLUSTERED 
		(
			[Lup_AB_Account_Departments_ID] ASC
		)
	)
End
GO

EXECute sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[Lup_AB_Account_Departments].[Date_Captured]'
GO
EXEC dbo.sp_bindefault @defname = N'[dbo].[df_User_ID]', @objname = N'[dbo].[Lup_AB_Account_Departments].[User_ID]'
GO
EXEC dbo.sp_bindefault @defname = N'[dbo].[df_User_Companies]', @objname = N'[dbo].[Lup_AB_Account_Departments].[AW_User_Companies_ID]'
GO
EXEC dbo.sp_bindefault @defname = N'[dbo].[df_Active]', @objname = N'[dbo].[Lup_AB_Account_Departments].[Slu_AW_Active_ID]'
GO

--Add Default Value
If NOT EXISTS
(
	SELECT 1
	FROM Lup_AB_Account_Departments
	WHERE Lup_AB_Account_Departments_ID = 1
)
BEGIN
	
	SET IDENTITY_INSERT [Lup_AB_Account_Departments] On

	INSERT INTO Lup_AB_Account_Departments
	(
		[Lup_AB_Account_Departments_ID],
		[Description]
	)
	VALUES
	(
		1,
		'<None>'
	)
	
	SET IDENTITY_INSERT [Lup_AB_Account_Departments] Off
END
GO

--Add to Lookup Editor List
If NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Lookup_Editor
	WHERE TableName = 'Lup_AB_Account_Departments'
)
BEGIN
	
	Declare @Sys_AW_Lookup_Editor_ID Int

	Set @Sys_AW_Lookup_Editor_ID = 0

	Select @Sys_AW_Lookup_Editor_ID = MAX(Sys_AW_Lookup_Editor_ID)
	From Sys_AW_Lookup_Editor

	Set @Sys_AW_Lookup_Editor_ID = @Sys_AW_Lookup_Editor_ID + 1
  	
	INSERT INTO Sys_AW_Lookup_Editor
	(
		Sys_AW_Lookup_Editor_ID,
		TableName,
		Caption,
		ColumnWidths,
		Slu_AW_Active_ID
	)
	VALUES
	(
		@Sys_AW_Lookup_Editor_ID,
		'Lup_AB_Account_Departments',
		'GL Account Departments',
		'0,7275,0,0,0,1005',
		1
	)

END
GO
--AB_Accounts
--Linked Lup_AB_Account_Departments_ID
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='AB_Accounts' AND
        C.Name='Lup_AB_Account_Departments_ID'
)
ALTER TABLE AB_Accounts ADD Lup_AB_Account_Departments_ID Int
GO
	
UPDATE AB_Accounts
SET Lup_AB_Account_Departments_ID = 1
WHERE ISNULL(Lup_AB_Account_Departments_ID,0) = 0
GO

-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Account_Departments_ID]'
-------------------------------------------------------
GO
--Alter AP_Inventory_Adjustments Table - Add Lup_AP_Product_Bins_ID
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_Inventory_Adjustments' AND
        C.Name='Lup_AP_Product_Bins_ID'
) 
ALTER TABLE AP_Inventory_Adjustments ADD Lup_AP_Product_Bins_ID Integer
GO

UPDATE AP_Inventory_Adjustments
SET Lup_AP_Product_Bins_ID = 1
Where ISNULL(Lup_AP_Product_Bins_ID,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Lup_AP_Product_Bins_ID]'
-------------------------------------------------------
GO
--Insert Consignment Stock Transaction Types
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Consignment Goods Received'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Consignment Goods Received',
		'PJCRV',
		0,
		0,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Consignment Goods Returned'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Consignment Goods Returned',
		'PJCRN',
		0,
		0,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Consignment Note'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Consignment Note',
		'PJCSN',
		1,
		0,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Consignment Sold'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Consignment Sold',
		'PJCSS',
		0,
		0,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AW_Transaction_Types
	WHERE [Description] = 'Consignment Returned'
) 
BEGIN
	INSERT Sys_AW_Transaction_Types
	(		
		[Description], 
		Type_Code, 
		POS_Used, 
		Cash_Up, 
		Factor
	)
	VALUES
	(
		'Consignment Returned',
		'PJCSR',
		0,
		0,
		1
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Customer_Product_Bins]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Customer_Product_Bins]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Product_Bins
--Purpose       : 
--Functionality : 
--REQUIRED in UI:CustomerID, UserID, CompanyID
--Date          :2016-07-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Select_Customer_Product_Bins]
    (
    	@Company_ID int,
    	@Customer_ID int
    )

AS

--EXEC sp_AC_Select_Customer_Product_Bins 0, 2, 567, 0

SET NOCOUNT ON

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

        SELECT
            a.AC_Product_Bins_ID AS [ID], 
            a.AC_Customers_ID AS [CustomerID],         -- REQUIRED AS IS
            a.Lup_AP_Product_Bins_ID AS [ProductBin], 
            a.Date_Captured AS [Date Captured], 
            a.[User_ID] AS [User],                   -- REQUIRED AS IS
            a.AW_User_Companies_ID AS [CompanyID],     -- REQUIRED AS IS 
            a.Slu_AW_Active_ID AS [Active]
        FROM AC_Product_Bins a
--            INNER JOIN AW_Users b
--                ON a.[User_ID] = b.AW_Users_ID
        WHERE a.AC_Customers_ID = @Customer_ID AND
              a.AW_User_Companies_ID = @Company_ID
        ORDER BY a.Date_Captured DESC

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Customer_Bin_Exceptions]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Customer_Bin_Exceptions]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Bin_Exceptions
--Purpose       :List products sold to customers with incorrect bin selection
--Functionality :Tyre Corporation. Customer should only be able to buy out of bins linked to them
--Date          :2016-07-28
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Bin_Exceptions]
    (
		@ChkAllCustomers	int,
		@CustomerID			int,
		@ChkDates			int,
		@StartDate			datetime,
		@EndDate			datetime,
		@ChkBin				int,
        @Bin_ID				int,
		@ShowException		tinyint,
        @Sort				tinyint,
        @CompanyID			int
    )
AS

-- EXEC sp_RPT_AC_Customer_Bin_Exceptions 0, '2013-01-01', '2016-06-01', 'Customer', 1

SET NOCOUNT ON

	DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '
    SET @sql = @sql + ' t.Transaction_Date AS [TranDate], '    
    SET @sql = @sql + ' p.Product_Code AS [Code], '        
    SET @sql = @sql + ' p.[Description] As [Product], '            
    SET @sql = @sql + ' d.Quantity As [Quantity], '                
    SET @sql = @sql + ' y.[Description] As [TranType], '   
    SET @sql = @sql + ' t.Transaction_Number AS [TranNo], '                     
    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 + ' RTRIM(LTRIM(ISNULL('' '' + u.UserName, ''''))) AS [User], '
	SET @sql = @sql + ' b.[Description] As [Bin] '	
	SET @sql = @sql + ' FROM AS_Transactions t '
	SET @sql = @sql + ' 	Inner Join AS_Transaction_Details d '
	SET @sql = @sql + ' 		On t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + ' 	Inner Join AC_Customers c '
	SET @sql = @sql + ' 		On t.AC_Customers_ID = c.AC_Customers_ID '
	SET @sql = @sql + ' 	Inner Join AW_Users u '
	SET @sql = @sql + ' 		On t.[User_ID] = u.AW_Users_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 Sys_AW_Transaction_Types y '
	SET @sql = @sql + ' 		On t.Sys_AW_Transaction_Types_ID = y.Sys_AW_Transaction_Types_ID '
	SET @sql = @sql + ' 	Inner Join Lup_AP_Product_Bins b '
	SET @sql = @sql + ' 		On d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID '

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

	IF @ShowException = 1
	BEGIN
		SET @sql = @sql + ' AND d.Lup_AP_Product_Bins_ID NOT IN (SELECT Lup_AP_Product_Bins_ID FROM AC_Product_Bins Where AC_Customers_ID = t.AC_Customers_ID AND SLU_AW_Active_ID = 1) '
	END
	
    IF @ChkAllCustomers = 0    --Single Customer Account
    BEGIN
        SET @sql = @sql + ' AND t.AC_Customers_ID = ' + CONVERT(varchar(10), @CustomerID) + ' '
    END

	IF @ChkBin = 0
	BEGIN
		SET @sql = @sql + ' AND d.Lup_AP_Product_Bins_ID = ' + CONVERT(varchar(10), @Bin_ID) + ' '
	END

    IF @Sort = 0        --Transaction Date
    BEGIN
        SET @sql = @sql + ' ORDER BY [TranDate] ASC '
    END

    IF @Sort = 1        --Transaction Number
    BEGIN
        SET @sql = @sql + ' ORDER BY [TranNo] ASC '
    END

    IF @Sort = 2        --Customer
    BEGIN
        SET @sql = @sql + ' ORDER BY [Customer] ASC '
    END

    IF @Sort = 3        --Product Code
    BEGIN
        SET @sql = @sql + ' ORDER BY [Code] ASC '
    END

    IF @Sort = 4        --Product Description
    BEGIN
        SET @sql = @sql + ' ORDER BY [Product] ASC '
    END

    IF @Sort = 5        --Product Bin
    BEGIN
        SET @sql = @sql + ' ORDER BY [Bin] ASC '
    END

	EXEC (@sql)
GO
IF NOT EXISTS
(
	SELECT Sys_AW_Reports_ID
	FROM Sys_AW_Reports
	WHERE Report_No = '324' 
	AND	Method_Name = 'Show_CustBinSales'
) 

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
	(
		3,
		0,
		'Customer Reports',
		'324',
		'Customer Product Bin Sales',
		'Customer Product Bin Sales',
		'SpSCustomerReports',
		'CInterface',
		'Show_CustBinSales'
	)
END
GO
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
     
     --RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan of current year  
     IF @YearEndMonthID = 12
       SET @StartYearID = @SelectedYearID
        
SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Update
--Purpose       :Updates address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-07-09
--Authors       :RL
--Mods
--V6.3	RL	2017-02-28	:Don't remove address details
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Update]
    (    	    	
    	@AS_Transactions_Address_Detail_ID	int,
    	@Inv_Customer_Name					varchar(100),
		@Inv_Address1						varchar(40),
		@Inv_Address2						varchar(40),
		@Inv_City							varchar(30),
		@Inv_Code							varchar(10),
		@Inv_Tax_Number						varchar(16),
		@Delivery_Address					varchar(40),
		@Delivery_Suburb					varchar(40),
		@Delivery_City						varchar(30),
		@Delivery_Post_Code					varchar(10),
		@User_ID							int,
		@AC_Customers_ID					int,
		@AS_Transactions_ID					int,
		@Company_ID							int		
    )
AS 

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

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

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

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	SELECT @Other_Record = COUNT(*)
	FROM AS_Transactions_Address ta
		INNER JOIN AS_Transactions_Address_Detail ad
			ON ta.AS_Transactions_Address_Detail_ID = ad.AS_Transactions_Address_Detail_ID
	WHERE ta.AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	AND AS_Transactions_ID <> @AS_Transactions_ID	
	
	--IF (@AW_YesNo_Invoice = 0 AND @AW_YesNo_Delivery_Address = 0)
	--BEGIN
	--	DELETE FROM AS_Transactions_Address_Detail WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--	DELETE FROM AS_Transactions_Address WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	--END
	--ELSE
	--BEGIN
	IF (@AS_Transactions_Address_Detail_ID = 0) OR (@Other_Record > 0)
	BEGIN	
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				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()
		
		IF @Other_Record = 0
		BEGIN
			INSERT INTO AS_Transactions_Address
				(
					AS_Transactions_ID, 
					AS_Transactions_Address_Detail_ID, 
					Date_Captured, 
					User_ID, 
					AW_User_Companies_ID
				)
			VALUES
				(
					@AS_Transactions_ID,
					@AS_Transactions_Address_Detail_ID,
					GETDATE(),
					@User_ID,
    				@Company_ID
    			)
    	END
    	ELSE
    	BEGIN
    		UPDATE AS_Transactions_Address
    		SET AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
    		WHERE AS_Transactions_ID = @AS_Transactions_ID
    	END
	END
	ELSE
	BEGIN	 
		UPDATE AS_Transactions_Address_Detail
		SET
			Customer_Name = @Inv_Customer_Name,
			Inv_Address1 = @Inv_Address1,
			Inv_Address2 = @Inv_Address2,
			Inv_Code = @Inv_Code,
			Inv_City = @Inv_City,
			Tax_Number = @Inv_Tax_Number,
			Delivery_Address = @Delivery_Address,
			Delivery_Suburb = @Delivery_Suburb,
			Delivery_City = @Delivery_City,
			Delivery_Post_Code = @Delivery_Post_Code
		WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
			  
	END
SET NOCOUNT ON
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_DayEnd_Export_Sales]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Export_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by EXPORT CUSTOMER by Filter
--Date          :2011/03/08
--Authors       :TB
--MODS:         :
--RL	V6.1	2015-02-19	:Removed Customer Account Type Check. Does not make sense???
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
    (
        @Filter varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Tax_Rate decimal(5,2),
            @TaxRate varchar(30)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


------------------------------------------------------------------------------
    --> Get the STANDARD VAT rate
------------------------------------------------------------------------------
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

--    SET @Tax_Rate = @Tax_Rate / 100

    SET @TaxRate = CONVERT(varchar(30), @Tax_Rate)
------------------------------------------------------------------------------


    SET @sql = ' SELECT '

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


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '


    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' tc.[Description] AS [TaxCode], '
    SET @sql = @sql + ' tc.Tax_Rate AS [TaxRate], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    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 + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    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 Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '          ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '

    IF @Filter = 'Type'
        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 @Filter = 'Groups'
        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 @Filter = 'Department'
        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 @Filter = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        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 @Filter = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        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 = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_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)  ' 
      --  '       c.Sys_AC_Account_Types_ID = 7 ' Export WTF????

    SET @sql = @sql + ' ORDER BY [Customer], [Filter], [TranDate] '

--PRINT @sql

EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Customers_InvDel]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_InvDel
--Purpose       :POS Customer Invoice and Delivery Address Details
--Date          :2013/08/08
--Authors       :RL
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

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

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

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

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

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

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

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_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
--V6.3	RL	2017-02-28	:Changed so that each document will have its own link in the address details table
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Insert]
    (	@AC_Customers_ID	int,	--RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID	
		@Company_ID	int,			--In POS code, Customer is sent through first
    	@AS_Transactions_ID int,
    	@Inv_Customer_Name varchar(100),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@Delivery_Address varchar(40),
		@Delivery_Suburb varchar(40),
		@Delivery_City varchar(30),
		@Delivery_Post_Code varchar(10),
		@User_ID	int
    )
AS 

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

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

	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
		 
	--V6.3 Each document will have its own link in the address details table
	--SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID
	--FROM AS_Transactions_Address_Detail
	--WHERE AC_Customers_ID = @AC_Customers_ID AND
	--	  Customer_Name = @Inv_Customer_Name AND
	--	  Inv_Address1 = @Inv_Address1 AND
	--	  Inv_Address2 = @Inv_Address2 AND
	--	  Inv_Code = @Inv_Code AND
	--	  Inv_City = @Inv_City AND
	--	  Tax_Number = @Inv_Tax_Number AND
	--	  Delivery_Address = @Delivery_Address AND
	--	  Delivery_Suburb = @Delivery_Suburb AND
	--	  Delivery_City = @Delivery_City AND
	--	  Delivery_Post_Code = @Delivery_Post_Code

	--IF @AS_Transactions_Address_Detail_ID = 0
	--BEGIN
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				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
--Column width used to be 50
ALTER TABLE AS_Transactions_Address_Detail ALTER  COLUMN Customer_Name Varchar(100) NULL
GO
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

	--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 WHEN @chkPOSPrintTradeName = 1
					THEN
						CASE WHEN ISNULL(Initials,'') = ''
						THEN
							CASE WHEN ISNULL(Firstnames,'') = ''
							THEN LTRIM(RTRIM(Surname))
								ELSE LTRIM(RTRIM(Surname)) + ' / ' + LTRIM(RTRIM(Firstnames))
							END
						ELSE
							CASE WHEN ISNULL(Firstnames,'') = '' 
							THEN LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) 
								ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials)) + ' / ' + LTRIM(RTRIM(Firstnames))
							END
						END
					ELSE
						CASE WHEN ISNULL(Initials,'') = ''
						THEN LTRIM(RTRIM(Surname))
							ELSE LTRIM(RTRIM(Surname)) + ', ' + LTRIM(RTRIM(Initials))
						END
					END,					
					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
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    	WHERE name = 'trg_AC_Customers_INS' 
    	AND type = 'TR'
)

DROP TRIGGER trg_AC_Customers_INS
GO
CREATE TRIGGER [trg_AC_Customers_INS] ON [AC_Customers]
FOR INSERT 
AS
BEGIN

	INSERT INTO AC_Product_Bins
	(
		AC_Customers_ID,
		Lup_AP_Product_Bins_ID,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID,
		Slu_AW_Active_ID
	)
	SELECT
		AC_Customers_ID,
		1,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID,
		Slu_AW_Active_ID
    FROM Inserted     
     
END
GO

INSERT INTO AC_Product_Bins
(
	AC_Customers_ID,
	Lup_AP_Product_Bins_ID,
	Date_Captured,
	[User_ID],
	AW_User_Companies_ID,
	Slu_AW_Active_ID
)
SELECT 
	AC_Customers_ID,
	1,
	GETDATE(),
	[User_ID],
	AW_User_Companies_ID,
	Slu_AW_Active_ID
FROM AC_Customers
WHERE AC_Customers_ID NOT IN (SELECT AC_Customers_ID FROM AC_Product_Bins)
GO

--Index On AC_Product_Bins.AC_Customers_ID
IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AC_Product_Bins_AC_Customers_ID'
)
DROP INDEX AC_Product_Bins.IX_AC_Product_Bins_AC_Customers_ID
GO
CREATE INDEX IX_AC_Product_Bins_AC_Customers_ID
   ON AC_Product_Bins (AC_Customers_ID)
	WITH FILLFACTOR = 80
GO
--AB Transaction Type - Cash Book - Tax
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AB_Transaction_Types
	WHERE [Description] = 'Cash Book - Tax Payment'
) 
BEGIN
	INSERT Sys_AB_Transaction_Types
	(		
		[Description], 
		Transaction_Code, 
		Sys_AB_Transaction_Categories_ID
	)
	VALUES
	(
		'Cash Book - Tax Payment',
		'CB Tax Pay',
		3
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AB_Transaction_Types
	WHERE [Description] = 'Cash Book - Tax Received'
) 
BEGIN
	INSERT Sys_AB_Transaction_Types
	(		
		[Description], 
		Transaction_Code, 
		Sys_AB_Transaction_Categories_ID
	)
	VALUES
	(
		'Cash Book - Tax Received',
		'CB Tax Rec',
		3
	)
END
GO

UPDATE AB_Control_Accounts
SET [Description] = 'TAX Control',
	User_Description = 'TAX Control'
WHERE Control_Number = '401'
GO

UPDATE Sys_AW_Reports
SET Report_Name = 'Zero TAX Sales by Customer',
	[Description] = 'Zero TAX Sales by Customer'
WHERE Report_No = '109'
GO

UPDATE Sys_AW_Reports
SET Report_Name = 'TAX Report',
	[Description] = 'TAX Report'
WHERE Report_No = '508'
GO

--AB Transaction Type - Accounts Receivable - Settlement
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AB_Transaction_Types
	WHERE [Description] = 'Accounts Receivable - Bad Debt'
) 
BEGIN
	INSERT Sys_AB_Transaction_Types
	(		
		[Description], 
		Transaction_Code, 
		Sys_AB_Transaction_Categories_ID
	)
	VALUES
	(
		'Accounts Receivable - Bad Debt',
		'AR Bad Debt',
		1
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Journals_Insert_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Journals_Insert_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Journals_Insert_Update
--Purpose       :Posts Customer Journals
--Functionality :Used in Customer Journals
--Parameters    :
--Date          :2002/02/26
--Authors       :TB
--Mods          :11/06/02 - Added UPDATE Customer Account_Balance
--              :11/06/18 - Removed INSERT of Date_Captured in AS_Transactions
--              :24/06/02 - Reduced @Comment to varchar(20) per DB Definition
--              :25/06/02 - Differentiate between Normal JNL and Interest JNL
--              :           in sp_AB_Insert_GL_Transactions with @GLTranTypeID
--              :NB NB NB   REQUIRES MOD TO ID=23 of Sys_AB_Transaction_Types
--              :07/07/02 - Removed GL UPDATE. This is done in the DAY-END sp:
--              :                sp_AS_Day_End
--              :28/07/02 - Put back GL Update (was never put into sp_AS_Day_End)
--              :07/01/03 - Put back update of AB_Accounts_ID in AS_Transactions
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :06/08/04 - Added Lup_AS_Cashiers_ID and insert @UserID to standarize
--2004.3.2      :17/10/06 - Added Customer Surname to GL Description
--2004.5.0      :25/01/11 - Renamed @ID to @@DocumentID, replaced SET with SELECT for Scope_Identity()
--              :           and added RETURN @DocumentID for Periodic Billing Journals
--V6.2	2016-08-02	:Added Accounts Receivable - Bad Debt for TAX Report distinction
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Customer_Journals_Insert_Update]
	(
		@RefNo varchar(20),
		@Date DateTime,
		@Comment varchar(20),
		@Amount money,
		@Tax money,
		@Total money,
		@Account int,
		@Month int, 
		@Year int,
		@TransactionType int,
		@FKID int,
		@CompanyID int,
		@UserID int
	)
AS     

SET NOCOUNT ON

    DECLARE @DocumentID int,
            @GLAccountID int,
            @GLTranTypeID tinyint,
            @GLSourceRef varchar(20),
            @NextGLTranID int,
            @Surname varchar(40),
            @GLDescription varchar(50),
            @CommentLen smallint

    IF @TransactionType = 5
        SET @GLTranTypeID = 22    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Journal
    ELSE
    IF @TransactionType = 15
        SET @GLTranTypeID = 23    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Interest
    ELSE
    --V6.2	Rl	2016-08-04 --Changed to display in own section on TAX report
    IF @TransactionType = 36
        SET @GLTranTypeID = 32    --Sys_AB_Transaction_Types_ID - Accounts Receivable - Bad Debt

	--V6.3 RL 2017-05-15 Fix. System does not pick up transaction type 36
   IF @TransactionType = 36
        SET @TransactionType = 5

-------------------------------------------------------------------------------
--> UPDATE CUSTOMER
-------------------------------------------------------------------------------
	INSERT AS_Transactions 
		(
	         Transaction_Number,
		     Transaction_Date,
	         [Amount] ,
	         Total_Tax_Amount,
	         Total_Amount,
	         AB_Accounts_ID ,
	         Comment,
	         Sys_AW_Transaction_Types_ID ,
	         AC_Customers_ID ,	
             Lup_AS_Cashiers_ID,
		     AW_User_Companies_ID,
		     [User_ID]
		)
	VALUES
		(
			@RefNo,
			@Date,
			@Amount,
			@Tax,
			@Total,
			@Account,
			@Comment,
			@TransactionType ,
			@FKID,
            @UserID,
			@CompanyID,
			@UserID
		)

    SELECT @DocumentID = Scope_Identity()


--> UPDATE Customer Account Balance
	UPDATE AC_Customers
    SET Account_Balance = Account_Balance + @Total
    WHERE AC_Customers_ID = @FKID


-------------------------------------------------------------------------------
--> UPDATE GL
-------------------------------------------------------------------------------

    SELECT @Surname = Surname
    FROM AC_Customers
    WHERE AC_Customers_ID = @FKID


    SET @CommentLen = LEN(@Comment) + 2
    SET @GLDescription = LEFT(LEFT(@Comment, 20) + ' ' + LEFT(@Surname, (50 - @CommentLen)), 50)


--> Create NORMAL JOURNAL header for the Year-End - 22 = Accounts Receivable - Journal
	EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    22,
                                    @CompanyID


    SELECT @GLAccountID = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 101	
	
--> INSERT a GL Transaction for the Debtors Control GL Account
    EXEC sp_AB_Insert_GL_Transactions
            @GLDescription,
            @GLTranTypeID,
            @GLAccountID,
            @Date,
            @RefNo,
            @Month,
            @Year,
            @DocumentID,
            @Total,
            @UserID,
            @CompanyID
		
	SET @Amount = -@Amount
	SET @Tax = -@Tax

--> INSERT a GL Transaction for the VAT GL Account
	IF @Tax <> 0 
		BEGIN
			SELECT @GLAccountID = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 401	
			
            EXEC sp_AB_Insert_GL_Transactions
                    @GLDescription,
                    @GLTranTypeID,
                    @GLAccountID,
                    @Date,
                    @RefNo,
                    @Month,
                    @Year,
                    @DocumentID,
                    @Tax,
                    @UserID,
                    @CompanyID
		END

--> INSERT a GL Transaction for the SELECTED GL Account
	EXEC sp_AB_Insert_GL_Transactions
            @GLDescription,
            @GLTranTypeID,
            @Account,
            @Date,
            @RefNo,
            @Month,
            @Year,
            @DocumentID,
            @Amount,
            @UserID,
            @CompanyID	




RETURN @DocumentID
GO
--Fix Previous Settlement discount GL Transactions to display in it's own section on the TAX Report
UPDATE AB_GL_Transactions
SET Sys_AB_Transaction_Types_ID = 24
WHERE Description Like '% Settlement %'
AND Sys_AB_Transaction_Types_ID = 22
GO

UPDATE AB_GL_Transactions
SET Sys_AB_Transaction_Types_ID = 24
WHERE Sys_AB_Transaction_Types_ID = 22
AND AB_Accounts_ID = (SELECT AB_Accounts_ID FROM AB_Control_Accounts WHERE Control_Number = '103')
GO

UPDATE AB_GL_Transactions
SET Sys_AB_Transaction_Types_ID = 25
WHERE Description Like '% Settlement %'
AND Sys_AB_Transaction_Types_ID = 8
GO

UPDATE AB_GL_Transactions
SET Sys_AB_Transaction_Types_ID = 25
WHERE Sys_AB_Transaction_Types_ID = 7
AND AB_Accounts_ID = (SELECT AB_Accounts_ID FROM AB_Control_Accounts WHERE Control_Number = '205')
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Supplier_Payment_GL_Clearing_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Supplier_Payment_GL_Clearing_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO                 
-------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Payment_GL_Clearing_Insert
--Purpose       :NEW Supplier Payment Creditors Clearing insert
--Functionality :INSERTS GL Transactions for:
--              :        1. Trade Creditors Control,
--              :        2. Trade Creditors Payment Clearing,
--              :        3. Settlement Discount Received
--              :        4. V.A.T. on Settlement Discount
--              :
--Date          :2002/07/21
--Authors       :TB
--MODS          :21/11/02 - Removed 'Supplier Payment: prefixed to GL Tran @Narration
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :16/12/03 - Changed @Month parameter from int to tinyint
--              :25/11/04 - Added new @TranRefNo input parameter to replace irrelevant
--              :           (last) @Supplier_Inv_No inserted into AB_Source_Ref
--              :           to XREF a Supplier PAYMENT in GL to its constituant parts
--              :14/12/04 - Appended ' Payment' to the GL @Narration
--2004.2.7      :01/04/06 - Changed GL TranType for Settlement AMOUNT and VAT
--              :           from 25 to 8 (AP Payment) for GL Popup
--              :01/04/06 - Changed GL Narration for each Settlement entry
--              :01/04/06 - Added TRIM(@Supplier_Name)
--2004.4.6      :12/08/09 - Added @Comment parameter
--2016.6.2	RL	:2016-08-04	:Changed Settlement discount from 8 to 25 ABTranType - AP Settlement
--							 So that it shows in its own section on TAX report
-------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AO_Supplier_Payment_GL_Clearing_Insert]
    (
    	@Invoices_Total money,
    	@Discount_Amount money,
    	@Payment_Total money,
        @Company_Banks_ID int,
    	@Transaction_Type_ID tinyint,
    	@Month tinyint, 
    	@Year int,
    	@AO_Transactions_ID int,
    	@UserID int,
        @CompanyID int,
        @TranRefNo varchar(20),
        @Comment varchar(20)
    )

AS

SET NOCOUNT ON

    DECLARE
        @Supplier_ID int,
        @Supplier_Name varchar(25),
        @DocDate datetime,
        @GLControlAccount int,
        @Narration varchar(50),
        @Settlement_VAT money,
        @Settlement_Ex_VAT money,
        @TaxRate decimal(5,2)


	SELECT @Supplier_ID = AO_Suppliers_ID,
           @DocDate = Document_Date
	FROM AO_Transactions
	WHERE AO_Transactions_ID = @AO_Transactions_ID
	
	SELECT @Supplier_Name = LEFT(RTRIM(LTRIM(ISNULL(Supplier_Name, ''))), 25) 
	FROM AO_Suppliers
	WHERE AO_Suppliers_ID = @Supplier_ID

	SET @Narration = LEFT(('Payment ' + @Supplier_Name + ' ' + @Comment), 50)


	BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

		BEGIN TRANSACTION

-------------------------------------------------------------------------------
    --Debit Trade Creditors Control
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 201    --Trade Creditors Control
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                     --ABTranType = A/P - Payment
                        @GLControlAccount,     --@AB_Accounts_ID
                        @DocDate,              --NEW
                        @TranRefNo,            --Next Payment Transaction Number
                        @Month,                --@AW_Months_ID
                        @Year,                 --@AW_Years_ID
                        @AO_Transactions_ID,   --@Transaction_Ref
                        @Invoices_Total,       --Invoices Total
                        @UserID,               --@User_ID
                        @CompanyID             --@Company_ID
    
            END

-------------------------------------------------------------------------------
    --Credit Trade Creditors Payment Clearing
-------------------------------------------------------------------------------
            BEGIN
    
                SELECT @GLControlAccount = AB_Accounts_ID
                FROM AB_Control_Accounts
                WHERE Control_Number = 207    --Trade Creditors Payment Clearing

                --Make the SIGN opposite (DR or CR) to Trade Creditors entry 
                SET @Payment_Total = (@Payment_Total * -1)
    
            --> Create GL TRANSACTION: DEBIT Creditors Control
                EXEC sp_AB_Insert_GL_Transactions
                        @Narration,
                        8,                     --ABTranType = AP Payment
                        @GLControlAccount,     --@AB_Accounts_ID
                        @DocDate,              --NEW
                        @TranRefNo,            --Next Payment Transaction Number
                        @Month,                --@AW_Months_ID
                        @Year,                 --@AW_Years_ID
                        @AO_Transactions_ID,   --@Transaction_Ref
                        @Payment_Total,        --Cheque Amount
                        @UserID,               --@User_ID
                        @CompanyID             --@Company_ID
    
            END

-------------------------------------------------------------------------------
    --SETTLEMENT DISCOUNT RECEIVED
-------------------------------------------------------------------------------
            IF @Discount_Amount <> 0
            --> Update SETTLEMENT DISCOUNT RECEIVED & VAT
                BEGIN
    
                --> (NEW 21 JUL 2002) VAT ON SETTLEMENT DISCOUNT --------
                    --Get the Current Tax Rate
                    SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                    FROM Sys_AW_Tax_Codes
                    WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                    
                    SET @Settlement_VAT = ROUND((@Discount_Amount * (@TaxRate / (100 + @TaxRate))) ,2)
                    SET @Settlement_Ex_VAT = (@Discount_Amount - @Settlement_VAT) 

                    --Changed the SIGN to opposite (DR or CR) in Back Office UI
--                     SET @Settlement_VAT = (@Settlement_VAT * -1)
--                     SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 205    --SETTLEMENT DISCOUNT RECEIVED

                    SET @Narration = LEFT((@Supplier_Name + ' - Settlement'), 50)

                --> Create GL TRANSACTION: CREDIT Settlement Discount Received
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            --V6.2	RL	2016-08-04	Changed to display in own section of TAX Report
                            25,                     --ABTranType AP Settlement
                            --8,                     --ABTranType = AP Payment
                            @GLControlAccount,     --@AB_Accounts_ID
                            @DocDate,              --NEW
                            @TranRefNo,            --Next Payment Transaction Number
                            @Month,                --@AW_Months_ID
                            @Year,                 --@AW_Years_ID
                            @AO_Transactions_ID,   --@Transaction_Ref
                            @Settlement_Ex_VAT,    --@Invoiced Amount
                            @UserID,               --@User_ID
                            @CompanyID             --@Company_ID
    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 401    --VAT Control

                    SET @Narration = LEFT((@Supplier_Name + ' - Settlement VAT'), 50)

                --> Create GL TRANSACTION: CREDIT VAT Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            --V6.2	RL	2016-08-04	Changed to display in own section of TAX Report
                            25,                     --ABTranType AP Settlement                            
                            --8,                     --ABTranType = AP Payment
                            @GLControlAccount,     --@AB_Accounts_ID
                            @DocDate,              --NEW
                            @TranRefNo,            --Next Payment Transaction Number
                            @Month,                --@AW_Months_ID
                            @Year,                 --@AW_Years_ID
                            @AO_Transactions_ID,   --@Transaction_Ref
                            @Settlement_VAT,       --@Invoiced Amount
                            @UserID,               --@User_ID
                            @CompanyID             --@Company_ID
    
                END

        COMMIT TRANSACTION

    END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_VAT_Report]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_VAT_Report]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AB_VAT_Report
--Purpose       :Monthly V.A.T. Report
--Date          :2004/11/07
--Authors       :TB
--Version       :1.0.0
--MODS          :
----2016.6.2 RL	2016-08-04	:Added option to exlude or exclude TAX payments or receipts
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AB_VAT_Report]
    (
        @Option					tinyint,
        @MonthID				tinyint,
    	@YearID					int,
        @ToMonthID				tinyint,
    	@ToYearID				int,
		@ChkShowExclusion		int,
        @ExclusionOption		int,
        @CompanyID				int
    )

AS

SET NOCOUNT ON

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


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


    SELECT @GLControlAccount = AB_Accounts_ID
    FROM AB_Control_Accounts
    WHERE Control_Number = 401    --VAT Control


    SET @sql = ' SELECT '

    SET @sql = @sql + '     gt.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     gt.AB_GL_Transactions_ID AS [GLTranID], '
    SET @sql = @sql + '     gt.AB_Transaction_Ref AS [GLRefID], '
    SET @sql = @sql + '     gt.Sys_AB_Transaction_Types_ID AS [TypeID],  '
    SET @sql = @sql + '     tt.[Description] AS [Type],  '
    SET @sql = @sql + '     tt.Transaction_Code AS [TypeCode],  '
    SET @sql = @sql + '     gt.AB_Source_Ref AS [GLSourceRefID], '
    SET @sql = @sql + '     gt.Description AS [Description], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gt.AB_Transaction_Date, 121)) AS [Date],  '
    SET @sql = @sql + '     m.[Description] AS [Month], '
    SET @sql = @sql + '     y.[Description] AS [Year], '
    SET @sql = @sql + '     gt.AB_Transaction_Amount AS [GLTranAmount], '
    SET @sql = @sql + '     gt.Date_Captured AS [Captured] '

    SET @sql = @sql + '     FROM AB_GL_Transactions gt '
    SET @sql = @sql + '     LEFT JOIN AB_Accounts gl '
    SET @sql = @sql + '         ON gt.AB_Accounts_ID = gl.AB_Accounts_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Months m '
    SET @sql = @sql + '         ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID '
    SET @sql = @sql + '     LEFT JOIN Slu_AW_Years y '
    SET @sql = @sql + '         ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID '
    SET @sql = @sql + '     LEFT OUTER JOIN Sys_AB_Transaction_Types tt '
    SET @sql = @sql + '         ON gt.Sys_AB_Transaction_Types_ID = tt.Sys_AB_Transaction_Types_ID '

--     SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
--     SET @sql = @sql + '         gt.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLControlAccount) + ' AND '
--     SET @sql = @sql + '         gt.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @MonthID) + ' AND '
--     SET @sql = @sql + '         gt.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @YearID) + ' '


    SET @sql = @sql + '     WHERE gt.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '           gt.AB_Accounts_ID = ' + CONVERT(varchar(10), @GLControlAccount) + ' AND '
    SET @sql = @sql + '           dbo.fn_AB_Get_Ending_GL_Period(gt.Slu_AW_Months_ID, gt.Slu_AW_Years_ID) BETWEEN ' + '''' + @StartPeriod + '''' + ' AND ' + '''' + @EndPeriod + ''''

	IF @ChkShowExclusion = 1
	BEGIN
		IF @ExclusionOption = 2 BEGIN
			SET @sql = @sql + '           AND gt.Sys_AB_Transaction_Types_ID IN (30, 31)'
		END
	END
	ELSE
	BEGIN
			SET @sql = @sql + '           AND gt.Sys_AB_Transaction_Types_ID NOT IN (30, 31)'
	END
	
	
    SET @sql = @sql + '     ORDER BY gt.Sys_AB_Transaction_Types_ID, gt.AB_Transaction_Date, gt.AB_Transaction_Ref '

    EXEC (@sql)


SET NOCOUNT OFF
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Discount_Price]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Discount_Price]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Discount_Price
--Purpose       :Returns stock quantity on consignment
--Parameters    :
--Date          :2015/04/14
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Discount_Price]
	(
        @Price							decimal(9,3),
        @Lup_AC_Discount_Categories_ID	int,
        @Lup_AP_Discount_Groups_ID		int
	)

RETURNS money

AS

	BEGIN
    	DECLARE @Discount_Percentage decimal(5,3)
    	DECLARE @Discount_Price		 decimal(9,3)

		SET @Discount_Percentage = 0
		
            SELECT @Discount_Percentage = ISNULL(Discount_Percentage, 0)
            FROM AS_Discount_Categories_Groups d
            WHERE d.Lup_AP_Discount_Groups_ID = @Lup_AP_Discount_Groups_ID AND
				  d.Lup_AC_Discount_Categories_ID = @Lup_AC_Discount_Categories_ID AND
                  d.Slu_AW_Active_ID = 1 

			SET @Discount_Price = @Price - ( (@Price / 100) * @Discount_Percentage)

    	RETURN @Discount_Price
    END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Stock_Take_Filtered]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Stock_Take_Filtered]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Stock_Take_Filtered
--Purpose       :Retrieves Inventory Stock Take sheet
--Date          :2004/09/05
--Authors       :TB
--Version       :1.0.0
--MODS:         :29/01/05 - Added [JobRes] field and narrowed Count fields by 3 spaces
--2004.4.1      :24/09/08 - Added dynamic [Reserved]
--2004.4.2      :23/01/09 - Reduced the spaces by 2 each in the [Count1] mask
--2004.4.6      :14/08/09 - Added Purchase Categories
--2016.6.2	RL  :2016-08-19 - Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Inventory_Stock_Take_Filtered]
	(
        @CompanyID int,
        @Filter varchar(100),
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @sql varchar(8000)


    SET @sql = ''
    
    
        SET @sql = ' SELECT '
    
        IF @Filter = 'Type'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Groups'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Department'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Supplier'
            SET @sql = @sql +
                ' o.AO_Suppliers_ID AS [HeaderID], ' +
                ' o.[Supplier_Name] AS [Filter], '
        ELSE
        IF @Filter = 'Manufacturer'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Location'
            SET @sql = @sql +
                ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'PurchCat'
            SET @sql = @sql +
                ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
                ' o.[Description] AS [Filter], '
        ELSE
        IF @Filter = 'Bin'
            SET @sql = @sql +
                ' d.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
                ' d.[Description] AS [Filter], '

        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' p.Pack_Size AS [Size], '
        SET @SQL = @SQL + ' p.On_Hand AS [Qty], '
        SET @SQL = @SQL + ' b.On_Hand AS [BinQty], '
        SET @SQL = @SQL + ' d.[Description] AS [Bin], '
        SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) AS [ConsQty], '
        SET @SQL = @SQL + ' CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved], '
        SET @SQL = @SQL + '''[               ][               ][                ]'' AS [Count1] '
        SET @SQL = @SQL + ' FROM AP_Products p '

        SET @sql = @sql + ' LEFT JOIN AP_Products_Bins b '
        SET @sql = @sql +   '     ON p.AP_Products_ID = b.AP_Products_ID '

        SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Bins d '
        SET @sql = @sql +   '     ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    
        IF @Filter = 'Type'
            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 @Filter = 'Groups'
            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 @Filter = 'Department'
            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 @Filter = 'Supplier'
            SET @sql = @sql +
                ' LEFT JOIN AO_Suppliers o ' +
                '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
        ELSE
        IF @Filter = 'Manufacturer'
            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 @Filter = 'Location'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Product_Locations o ' +
                '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
        ELSE
        IF @Filter = 'PurchCat'
            SET @sql = @sql +
                ' LEFT JOIN Lup_AP_Purchase_Categories o ' +
                '     ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '

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


        IF @OnHandOnly = 1
            BEGIN
                --> This code causes Query Timeout !!!!!!!
--                 SET @sql = @sql + ' AND ' + ' (p.On_Hand <> 0 ' +
--                                             ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
                SET @sql = @sql + ' AND ' + ' p.On_Hand <> 0 '
            END


        IF @NonStock = 1
            BEGIN
                SET @sql = @sql + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


        IF @Sort = 1
            BEGIN
                SET @sql = @sql + ' ORDER BY [Filter], [Code] '
            END
        ELSE
            BEGIN
                SET @sql = @sql + ' ORDER BY [Filter], [Product] '
            END


    EXEC (@SQL)



SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Stock_Take]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Stock_Take]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sp_RPT_AP_Inventory_Stock_Take 1, -1, 8, -1, -1, -1, -1, 0, 0, 0
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Stock_Take
--Purpose       :Retrieves Inventory Stock Take sheet
--Date          :2004/06/08
--Authors       :TB
--MODS:         :29/01/05 - Added [JobRes] field and narrowed Count fields by 3 spaces
--2004.4.1      :24/09/08 - Added dynamic [Reserved]
--2004.4.2      :23/01/09 - Reduced the spaces by 2 each in the [Count1] mask
--2004.4.6      :14/08/09 - Added Purchase Categories
--2016.6.2	RL  :2016-08-19 - Added Product Bins and Consignment
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Inventory_Stock_Take]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1,
      	@BinID int = -1,
        @OnHandOnly int,
        @Sort int,
        @NonStock int
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @SQL varchar(2000)

	SET @Filter = ''
    SET @SQL = ''


    	IF @SupplierID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                    convert(varchar(20), @SupplierID)
    		END
    --> Manufacturer
    	IF @ManufacturerID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                    convert(varchar(20), @ManufacturerID)
    		END
    --> Type
    	IF @TypeID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                    convert(varchar(20), @TypeID)
    		END
    --> Group
    	IF @GroupID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                    convert(varchar(20), @GroupID)
    		END
    --> Department
    	IF @DepartmentID > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                    convert(varchar(20), @DepartmentID)
    		END
    --> Location
    	IF @LocationID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                    convert(varchar(20), @LocationID)
        	END
    --> PurchCat
    	IF @PurchCatID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                    convert(varchar(20), @PurchCatID)
        	END
    --> Bin
    	IF @BinID  > 0 
    		BEGIN

    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' b.Lup_AP_Product_Bins_ID = ' +
                                    convert(varchar(20), @BinID)
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' b.Lup_AP_Product_Bins_ID = ' +
                                    convert(varchar(20), @BinID)
        	END


		IF @Filter = ''
            BEGIN
				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END
		ELSE
            BEGIN
				SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                                convert(varchar(20), @CompanyID)
            END

        IF @OnHandOnly = 1
            BEGIN
    			IF @Filter = ''
    				SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                                    convert(varchar(20), @CompanyID) +
                                  ' AND ' + ' (p.On_Hand <> 0 ' +
                                  ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
    			ELSE
    				SET @Filter = @Filter + ' AND ' + ' (p.On_Hand <> 0 ' +
                                            ' OR CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) <> 0) '
            END


        IF @NonStock = 1
            BEGIN
                SET @Filter = @Filter + ' AND ' + ' p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
            END


    	SET @SQL = 'SELECT '
        SET @SQL = @SQL + ' p.AW_User_Companies_ID AS [CompanyID], '
        SET @SQL = @SQL + ' p.AP_Products_ID AS [ID], '
        SET @SQL = @SQL + ' p.[Description] AS [Product], '
        SET @SQL = @SQL + ' p.Product_Code AS [Code], '
        SET @SQL = @SQL + ' p.Pack_Size AS [Size], '
        SET @SQL = @SQL + ' p.On_Hand AS [Qty], '
        SET @SQL = @SQL + ' b.On_Hand AS [BinQty], '
        SET @SQL = @SQL + ' d.[Description] AS [Bin], '
        SET @SQL = @SQL + ' dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) AS [ConsQty], '        
        SET @SQL = @SQL + ' CONVERT(decimal(12, 3), dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)) as [Reserved], '
        SET @SQL = @SQL + '''[               ][               ][                ]'' AS [Count1] '

        SET @SQL = @SQL + ' FROM AP_Products p '
        
        SET @sql = @sql + ' LEFT JOIN AP_Products_Bins b '
        SET @sql = @sql +   '     ON p.AP_Products_ID = b.AP_Products_ID '

        SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Bins d '
        SET @sql = @sql +   '     ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '
        
        SET @SQL = @SQL + @Filter


        IF @Sort = 1
            BEGIN
                SET @SQL = @SQL + ' ORDER BY p.Product_Code '
            END
        ELSE
            BEGIN

                SET @SQL = @SQL + ' ORDER BY p.[Description] '
            END


    EXEC (@SQL)
--Select @SQL


SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Received_CRV]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Received_CRV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Select_Received_CRV
--Purpose       :Fetches all CRV that have already been received for the specified supplier 
--Functionality :SELECT 
--Parameters    :@Supplier_ID
--Date          :2015/03/25
--Authors       :RL
--MODS          :
--------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Received_CRV]
    (
    	@SupplierID int = 0,
    	@Company_ID int			
    )

AS

	BEGIN
	
		SELECT AO_GRV_ID AS [ID],
    			Sys_AW_Transaction_Types_ID,
    			AO_Suppliers_ID AS [Suppliers ID],
    			AO_Orders_ID AS [Order],
                AO_GRV_ID AS [CRV],
    			Date_Received AS [Date Received],
    			Delivery_Note_Number AS [Del Note No],
    			Supplier_Reference AS [Suppliers Ref],
    			Trade_Discount_Total AS [Trade Disc],
    			Rebate_Discount_Total AS [Rebate Disc],
    			Other_Discount_Total AS [Other Disc],
    			Net_Amount AS [Net],
    			Total_Tax_Amount AS [Tax],
    			Total_Amount AS [Total],
    			Date_Captured AS [Date Captured],
    			[User_ID] AS [User ID],
    			AW_User_Companies_ID AS [Company],
    			Slu_AW_Active_ID AS [Active]
		FROM AO_GRV g
		WHERE AO_Suppliers_ID = @SupplierID AND
			Sys_AW_Transaction_Types_ID = 31 AND
			AW_User_Companies_ID = @Company_ID
		ORDER BY AO_GRV_ID DESC
		
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9960]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9960]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9960
--Purpose       :Wipe all CUSTOMER Transaction tables
--              :
--Parameters    :
--Date          :2002/02/11
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------


--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--AC_Customers not cleared
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

CREATE PROCEDURE [dbo].[sp_AW_9960]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AS_Transactions_AW_Comments]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AS_Transactions] DROP CONSTRAINT FK_AS_Transactions_AW_Comments

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Assets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Assets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Contract_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Contract_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Customer_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Associates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Associates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Auditors]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Auditors]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Balance_Sheets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Balance_Sheets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bankers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bankers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Credit_Limits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Credit_Limits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Default]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Default]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_ITCScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_ITCScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Income_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Income_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Info_Reports]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Info_Reports]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Judgements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Judgements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_KIScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_KIScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Motion_Roll]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Motion_Roll]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Notarial_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Notarial_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principal_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principal_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_RD_Cheques]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_RD_Cheques]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Ratings]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Ratings]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Shareholders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Shareholders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Status]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Status]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Trade_References]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Trade_References]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Comments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Comments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Master_Controller]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Master_Controller]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Messages]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Messages]

    
    CREATE TABLE [dbo].[AC_Assets] (
    	[AC_Assets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Asset_Types_ID] [smallint] NULL ,
    	[Reg_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[VIN_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage_Date] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Qty] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AS_Transactions_ID] [int] NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Contract_Prices] (
    	[AC_Contract_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Perc] [decimal](9, 3) NULL ,
    	[Discount_Amount] [money] NULL ,
    	[MinSaleQty] [decimal](9, 3) NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Ageing_Temp] (
    	[AC_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Customer_Ageing] (
    	[AC_Enterprise_Customer_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Associates] (
    	[AC_History_Associates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Associate_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Association_Types_ID] [smallint] NULL ,
    	[Shareholding_Percentage] [decimal](7, 2) NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Date_Acquired] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Auditors] (
    	[AC_History_Auditors_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Firm_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Audit_Manager] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_Date] [datetime] NULL ,
    	[Slu_AC_Profession_Types_ID] [smallint] NULL ,
    	[Slu_AC_Auditor_Rankings_ID] [smallint] NULL ,
    	[Profession_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Profession_Date_Changed] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Balance_Sheets] (
    	[AC_History_Balance_Sheets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Property_Plant_and_Equipment] [money] NULL ,
    	[Investment_Property] [money] NULL ,
    	[Investments_and_Loans] [money] NULL ,
    	[Investments_and_Finance_Leases] [money] NULL ,
    	[Forward_Exchange_Contract_Asset] [money] NULL ,
    	[Inventories] [money] NULL ,
    	[Trade_and_Other_Receivables] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Cash_and_Cash_Equivalents] [money] NULL ,
    	[Issued_Capital] [money] NULL ,
    	[Reserves] [money] NULL ,
    	[Accumulated_Profit_Loss] [money] NULL ,
    	[Interest_Bearing_Borrowings] [money] NULL ,
    	[Deferred_Taxation] [money] NULL ,
    	[Retirement_Benefit_Obligations] [money] NULL ,
    	[Trade_and_Other_Payables] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Dividend_Declared] [money] NULL ,
    	[Bank_Overdraft] [money] NULL ,
    	[Overdraft_Facility] [money] NULL ,
    	[Current_portion_of_Interest_Bearing_Borrowings] [money] NULL ,
    	[Warranty_Provision] [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]

    
    CREATE TABLE [dbo].[AC_History_Bankers] (
    	[AC_History_Bankers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Banks_ID] [smallint] NULL ,
    	[Bank_Branch] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Branch_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bank_Codes_ID] [tinyint] NULL ,
    	[Bank_Code_Amount] [money] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Banker_Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Opened] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Bonds] (
    	[AC_History_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Repayment_Period] [decimal](3, 0) NULL ,
    	[Repayment_Amount] [money] NULL ,
    	[Effective_Date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Credit_Limits] (
    	[AC_History_Credit_Limits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[New_Limit] [money] NULL ,
    	[Limit_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Default] (
    	[AC_History_Default_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Adverse_Reasons_ID] [int] NULL ,
    	[Adverse_Source] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Dispute_Amount] [money] NULL ,
    	[Days_Overdue] [int] NULL ,
    	[Adverse_Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_ITCScores] (
    	[AC_History_ITCScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_ITC_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,    	
    	[Effective_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Income_Statements] (
    	[AC_History_Income_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Revenue] [money] NULL ,
    	[Cost_of_Sales] [money] NULL ,
    	[Other_Income] [money] NULL ,
    	[Fleet_Rental] [money] NULL ,
    	[Distribution_Expenses] [money] NULL ,
    	[Auditors_Remuneration] [money] NULL ,
    	[Depreciation] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Profit_Loss_on_disposal_of_Assets] [money] NULL ,
    	[Permanent_decline_in_value_of_Investment_Property] [money] NULL ,
    	[Fees_for_Services] [money] NULL ,
    	[Rental_on_Operating_Leases] [money] NULL ,
    	[Forex_Gains_Losses] [money] NULL ,
    	[Staff_Costs] [money] NULL ,
    	[Other_Long_Term_Employee_Benefits] [money] NULL ,
    	[Directors_Emoluments] [money] NULL ,
    	[Other_Expenses] [money] NULL ,
    	[Financing_Costs] [money] NULL ,
    	[Financing_Costs_Capitalized] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Extraordinary_Items] [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]

    
    CREATE TABLE [dbo].[AC_History_Info_Reports] (
    	[AC_History_Info_Reports_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Info_Report_Types_ID] [smallint] NULL ,
    	[Report_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Judgements] (
    	[AC_History_Judgements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Defendant_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Plaintiff_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Judgement_Amount] [money] NULL ,
    	[Case_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Of_Judgement] [datetime] NULL ,
    	[Default_Judgement] [bit] NULL ,
    	[Date_Rescinded] [datetime] NULL ,
    	[Rescindment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Abandoned] [datetime] NULL ,
    	[Abandonment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_KIScores] (
    	[AC_History_KIScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_KI_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Motion_Roll] (
    	[AC_History_Motion_Roll_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Lawsuit_Types_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Respondent_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Applicant] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Application_Amount] [money] NULL ,
    	[Case_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Item_Number] [tinyint] NULL ,
    	[Hearing_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Notarial_Bonds] (
    	[AC_History_Notarial_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Effective_date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] 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]

    
    CREATE TABLE [dbo].[AC_History_Principal_Properties] (
    	[AC_History_Principal_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[AC_History_Principals_ID] [int] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Principals] (
    	[AC_History_Principals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[ID_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Principal_Types_ID] [smallint] NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[E_Mail] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Appointed] [datetime] NULL ,
    	[Date_Terminated] [datetime] NULL ,
    	[Primary_Function] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Comments] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Ind] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Properties] (
    	[AC_History_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_RD_Cheques] (
    	[AC_History_RD_Cheques_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Cheque_Amount] [money] NULL ,
    	[Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Ratings] (
    	[AC_History_Ratings_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Ratings_ID] [smallint] NULL ,
    	[Rating_Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Shareholders] (
    	[AC_History_Shareholders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Shareholder_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Interest_Percent] [decimal](7, 2) NULL ,
    	[Number_Of_Shares] [int] NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Members_Contribution] [money] NULL ,
    	[Par_Value_Of_Holding] [money] NULL ,
    	[Estimated_Valuation] [money] NULL ,
    	[Controlling_Shareholder] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Parent_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Holding_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Status] (
    	[AC_History_Status_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AC_Account_Status_ID] [smallint] NULL ,
    	[Status_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] 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]

    
    CREATE TABLE [dbo].[AC_History_Trade_References] (
    	[AC_History_Trade_References_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Security_Types_ID] [smallint] NULL ,
    	[Date_of_Reference] [datetime] NULL ,
    	[Supplier_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Position] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Telephone_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Period_Known] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Average_per_Month] [money] NULL ,
    	[Reference_Comments] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Highest_Amount] [money] NULL ,
    	[Account_Limit] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Given] [smallint] NULL ,
    	[Terms_Taken] [smallint] NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Past_Due_Amount] [money] NULL ,
    	[Limit_Of_Guarantee] [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]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail] (
    	[AC_Periodic_Billing_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] (
    	[AC_Periodic_Billing_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[AC_Periodic_Billing_Detail_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Header] (
    	[AC_Periodic_Billing_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details] (
    	[AC_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL     	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
    	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_Temp_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements] (
    	[AC_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements_Temp] (
    	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AW_Comments] (
    	[AW_Comments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NULL ,
    	[Comment] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Master_Controller] (
    	[Log_AC_Master_Controller_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NOT NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NOT NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AC_Severity_Levels_ID] [tinyint] NULL ,
    	[Sys_AC_Message_Types_ID] [smallint] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Messages] (
    	[Log_AC_Messages_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Message_Date] [datetime] NULL ,
    	[Dispatch_Date] [datetime] NULL ,
    	[User_CRM_ID] [int] NULL ,
    	[User_Controller_ID] [int] NULL ,
    	[Addressee] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Send_To] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Balance] [money] NULL ,
    	[Overdue] [money] NULL ,
    	[Credit_Terms] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Of_Sale] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Method] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Subject] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address_List] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Errors] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_History_Auditors] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Auditors] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Auditors_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Balance_Sheets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Balance_Sheets] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Balance_Sheets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bankers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bankers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bankers_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bonds] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bonds] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Credit_Limits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Credit_Limits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Credit_Limits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Default] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Default] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Default_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_ITCScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_ITCScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_ITCScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Income_Statements] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Income_Statements] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Income_Statements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Info_Reports] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Info_Reports] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Info_Reports_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_KIScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_KIScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_KIScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Ratings] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Ratings] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Ratings_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Status] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Status] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Status_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Trade_References] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Trade_References] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Trade_References_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AW_Comments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Comments] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Comments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Master_Controller] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Master_Controller] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Master_Controller_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Messages] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Messages] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Messages_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_Customer_Assets] ON [dbo].[AC_Assets]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AC_Contract_Customers_Products] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID], [AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Ageing_Temp] ON [dbo].[AC_Enterprise_Ageing_Temp]([Filter], [FullName], [Customer_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Customer_Ageing] ON [dbo].[AC_Enterprise_Customer_Ageing]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details] ON [dbo].[AC_Statement_Details]([AC_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details_Temp] ON [dbo].[AC_Statement_Details_Temp]([AC_Statement_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_ID] ON [dbo].[AC_Statements]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_Temp] ON [dbo].[AC_Statements_Temp]([AC_Statements_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Assets] ADD 
    	CONSTRAINT [PK_AC_Assets] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Assets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Contract_Prices] ADD 
    	CONSTRAINT [PK_AC_Contract_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Contract_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_Contract_Prices_Customers_ID] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Enterprise_Customer_Ageing] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Customer_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Customer_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Associates] ADD 
    	CONSTRAINT [PK_AC_History_Associates] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Associates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Judgements] ADD 
    	CONSTRAINT [PK_AC_History_Judgements] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Judgements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Motion_Roll] ADD 
    	CONSTRAINT [PK_AC_History_Motion_Roll] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Motion_Roll_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Notarial_Bonds] ADD 
    	CONSTRAINT [PK_AC_History_Notarial_Bonds] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Notarial_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principal_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Principal_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principal_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principals] ADD 
    	CONSTRAINT [PK_AC_History_Principals] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principals_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_RD_Cheques] ADD 
    	CONSTRAINT [PK_AC_History_RD_Cheques] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_RD_Cheques_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Shareholders] ADD 
    	CONSTRAINT [PK_AC_History_Shareholders] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Shareholders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AC_Statement_Details_Key] ON [dbo].[AC_Statement_Details]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AC_Statements_Customers_ID] ON [dbo].[AC_Statements]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser

    --Defaults AC_Assets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Assets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Assets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Assets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Assets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Contract_Prices
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Contract_Prices].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Contract_Prices].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Contract_Prices].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Contract_Prices].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Perc]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Contract_Prices].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Unit_Price]'
   
    setuser

    
    setuser
    --Defaults AC_Enterprise_Ageing_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Payment]'   
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[180+Days]'  
    
    setuser

    
    setuser
    --Defaults AC_Enterprise_Customer_Ageing
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Enterprise_Customer_Ageing].[CompanyID]'

    setuser

    
    setuser
    --Defaults AC_History_Associates
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Associates].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Associates].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Associates].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Associates].[Slu_AW_Active_ID]'
    
    setuser

   
    setuser
    --Defaults AC_History_Auditors
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Auditors].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Auditors].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Auditors].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Auditors].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Balance_Sheets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Balance_Sheets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Balance_Sheets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Balance_Sheets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Balance_Sheets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bankers
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bankers].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bankers].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bankers].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bankers].[Slu_AW_Active_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_History_Bankers].[Bank_Code_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AC_Bank_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bonds].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bonds].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Credit_Limits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Credit_Limits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Credit_Limits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Credit_Limits].[AW_User_Companies_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Credit_Limits].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Default
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Default].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Default].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Default].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Default].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_ITCScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_ITCScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_ITCScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_ITCScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_ITCScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Income_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Income_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Income_Statements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Income_Statements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Income_Statements].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    --Defaults AC_History_Info_Reports
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Info_Reports].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Info_Reports].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Info_Reports].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Info_Reports].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Judgements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Judgements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Judgements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Judgements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Judgements].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_KIScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_KIScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_KIScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_KIScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_KIScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Motion_Roll
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Motion_Roll].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Motion_Roll].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Motion_Roll].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Motion_Roll].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Notarial_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Notarial_Bonds].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Notarial_Bonds].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Notarial_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Notarial_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principal_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principal_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principal_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principal_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principal_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principals
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principals].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principals].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principals].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principals].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_RD_Cheques
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_RD_Cheques].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_RD_Cheques].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_RD_Cheques].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_RD_Cheques].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Ratings
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Ratings].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Ratings].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Ratings].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Ratings].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Shareholders
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Shareholders].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Shareholders].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Shareholders].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Shareholders].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Status
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Status].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Status].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Status].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Status].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Trade_References
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Trade_References].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Trade_References].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Trade_References].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Trade_References].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail].[Slu_AW_Active_ID]'
    
        

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AC_Customers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Comment]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Email]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Notes]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Ref_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Transaction_Date]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail_Splits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail_Splits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail_Splits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail_Splits].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail_Splits].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[AP_Products_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Unit_Price]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Header
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Header].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Header].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Header].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Posting_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AC_Periodic_Billing_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AC_Periodic_Billing_Header].[Slu_AW_Years_ID]'
    
    setuser


    setuser
    --Defaults AC_Statement_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statement_Details_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Statements_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]' 
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'

	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
	
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
    
    setuser

    
    setuser
    --Defaults AW_Comments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Comments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Comments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Comments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Comments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults Log_AC_Master_Controller
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Master_Controller].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Master_Controller].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Master_Controller].[AW_User_Companies_ID]'

      
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AC_Message_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AW_Delivery_Methods_ID]'

    setuser

    
    setuser
    --Defaults Log_AC_Messages
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Messages].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Messages].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Messages].[AW_User_Companies_ID]'
    
    setuser

  
    SET @ReturnValue = 1
 
RETURN @ReturnValue

SET NOCOUNT OFF    
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9900]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9900]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9900
--Purpose       :Wipe all SALES Transaction tables
--              :
--Parameters    :
--Date          :2002/04/19
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AW_9900]
AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

    SET @ReturnValue = 0

BEGIN

    --First wipe the customer balances
    UPDATE AC_Customers SET Account_Balance = 0,
                            Current_Balance = 0,
                            Days_30 = 0,
                            Days_60 = 0,
                            Days_90 = 0,
                            Days_120 = 0,
                            Days_150 = 0,
                            Days_180 = 0
 

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Cash_Ups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Cash_Ups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Day_Ends]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Day_Ends]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Customer_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_GP]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales_All]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Sales_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Sales_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Till_Payouts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Till_Payouts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Sources]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref_Sources]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address]

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address_Detail]
 
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Details_Consignment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Details_Consignment]
 
    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Cash_Ups] (
    	[AS_Cash_Ups_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Cashier_ID] [int] NULL ,
    	[Lup_AS_Tills_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [int] NULL ,
    	[Slu_AS_Coinage_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Slu_AW_Active_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Day_Ends] (
    	[AS_Day_Ends_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Day_End] [smalldatetime] NOT NULL ,
    	[AB_Transaction_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] 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]

    
    CREATE TABLE [dbo].[AS_Enterprise_Customer_Sales] (
    	[AS_Enterprise_Customer_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_GP] (
    	[AS_Enterprise_GP_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[TotalSales] [money] NULL ,
    	[TotalCost] [money] NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales] (
    	[AS_Enterprise_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales_All] (
    	[AS_Enterprise_Sales_All_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Sales_Order_Details] (
    	[AS_Sales_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Shipping_Cost] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[Promo_Price] [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]

    
    CREATE TABLE [dbo].[AS_Till_Payouts] (
    	[AS_Till_Payouts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Payout_Type_ID] [tinyint] NULL ,
    	[AB_Account_DR_ID] [int] NULL ,
    	[AB_Account_CR_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Description] [varchar] (36) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Narration] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Day_End] [smalldatetime] 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]

    
    CREATE TABLE [dbo].[AS_Transaction_Details] (
    	[AS_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Original_Price] [money] NULL ,
    	[Original_Discount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Commission_Amount] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[AS_Job_References_ID] [int] NULL ,
    	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[TDHeader] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[TDDetail] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL ,
    	[Consignment_Left] [decimal](9, 3) NULL ,
    	[Lup_AP_Product_Bins_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Payments] (
    	[AS_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[Slu_AS_Card_Institutions_ID] [int] NULL ,
    	[Payor_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Expiry_Date] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Authorisation_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Banked] [smalldatetime] 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]

    
    CREATE TABLE [dbo].[AS_Transaction_Sources] (
    	[AS_Transaction_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Numbers] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions] (
    	[AS_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total_Cost] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Discount_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Expiry_Date] [smalldatetime] NULL ,
    	[Version_Number] [smallint] NULL ,
    	[Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Lup_AS_Marketing_Indicators_ID] [int] NULL ,
    	[Lup_AW_Stores_ID] [smallint] NULL ,
    	[Lup_AW_Workstations_ID] [smallint] NULL ,
    	[Lup_AS_Tills_ID] [smallint] NULL ,
    	[Lup_AS_Cashiers_ID] [smallint] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Slu_AW_Currencies_ID] [smallint] NULL ,
    	[Old_Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Cancelled_User_ID] [int] NULL ,
    	[Cancelled_DateTime] [datetime] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Transmitted] [datetime] 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]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling] (
    	[AS_Transactions_CBilling_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Network_Identity_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Original_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Manufacturer_Code] [varchar] (18) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Lup_AP_Fail_Reasons_ID] [smallint] NULL ,
    	[Item_No] [smallint] NULL ,
    	[Authorization_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Odometer_Reading] [varchar] (7) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Client_ID_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AP_Claim_Codes_ID] [smallint] NULL ,
    	[Xmit_Date] [datetime] NULL ,
    	[Xmit_File] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling_Temp] (
    	[AS_Transactions_CBilling_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[cat_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_date] [datetime] NULL ,
    	[qty] [decimal](9, 3) NULL ,
    	[amount] [money] NULL ,
    	[gls_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[narr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stock_group] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_apply] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[sys_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[updated] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[interfaced] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_age_month] [smallint] NULL ,
    	[stock_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[area] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_alpha] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_amount] [money] NULL ,
    	[cost_amount] [money] NULL ,
    	[rep_comm] [money] NULL ,
    	[process_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[acct_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[disc_amnt] [money] NULL ,
    	[std_sell_price] [money] NULL ,
    	[drs_trs_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_type] [smallint] NULL ,
    	[acc_month] [smallint] NULL ,
    	[acc_year] [smallint] NULL ,
    	[con_acct_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_int01] [smallint] NULL ,
    	[cntno] [smallint] NULL ,
    	[line_disc1] [decimal](9, 3) NULL ,
    	[line_disc2] [decimal](9, 3) NULL ,
    	[stock_sell1] [money] NULL ,
    	[no_of_deals] [smallint] NULL ,
    	[zz_date01] [datetime] NULL ,
    	[zz_date02] [datetime] NULL ,
    	[zz_date03] [datetime] NULL ,
    	[special_instr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_flag] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_exempt_member] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[cmonth] [smallint] NULL ,
    	[cyear] [smallint] NULL ,
    	[rep_call_status] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drsdiv_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_date] [datetime] NULL ,
    	[creation_time] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_userid] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_proc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[item_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[qty2] [decimal](9, 3) NULL ,
    	[deposit_amount] [decimal](9, 3) NULL ,
    	[job_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[line_disc_amnt] [decimal](9, 3) NULL ,
    	[carhire_cntno] [smallint] NULL ,
    	[currency] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[exch_rate] [money] NULL ,
    	[cyear_month] [smallint] NULL ,
    	[zz_date04] [datetime] NULL ,
    	[zz_date05] [datetime] NULL ,
    	[zz_int02] [smallint] NULL ,
    	[zz_int03] [smallint] NULL ,
    	[zz_int04] [smallint] NULL ,
    	[zz_int05] [smallint] NULL ,
    	[zz_dec01] [decimal](9, 3) NULL ,
    	[zz_dec02] [decimal](9, 3) NULL ,
    	[zz_dec03] [decimal](9, 3) NULL ,
    	[zz_dec04] [decimal](9, 3) NULL ,
    	[zz_dec05] [decimal](9, 3) NULL ,
    	[zz_log01] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log02] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log03] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log04] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log05] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log06] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log07] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char01] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char02] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char03] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char05] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_glstrs] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_history] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[dumped] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[company_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[prd_grp_descr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stk_descry] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[status_ind] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments3] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments4] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments5] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments6] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments7] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments8] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[database_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[system_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_reg_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[email] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_cell_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_email_address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Transactions] (
    	[AS_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AS_Transactions_ID] [int] NULL ,
    	[Destination_AS_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] 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]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref] (
    	[AS_Transactions_Xref_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AW_YesNo_Checked_ID] [tinyint] NULL ,
    	[Checked_User_ID] [int] 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]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref_Sources] (
    	[AS_Transactions_Xref_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_Xref_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] 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]



	CREATE TABLE [dbo].[AS_Transactions_Address](
		[AS_Transactions_Address_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transactions_ID] [int] NOT NULL,
		[AS_Transactions_Address_Detail_ID] [int] NOT NULL,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL
	) ON [PRIMARY]


	CREATE TABLE [dbo].[AS_Transactions_Address_Detail](
		[AS_Transactions_Address_Detail_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Inv_Address1] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Address2] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Address] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Suburb] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Post_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		[Customer_Name] [varchar](100) NULL,
		[Tax_Number] [varchar](16) NULL,
		[AW_YesNo_Delivery_Address] [tinyint] NULL,
		[AW_YesNo_Invoice] [tinyint] NULL
	) ON [PRIMARY]  
  
   
	CREATE TABLE [AS_Transaction_Details_Consignment](
		[AS_Transaction_Details_Consignment_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transaction_Details_ID] [int] NOT NULL,
		[Consignment_ID] [int] NULL,
		[Sys_AW_Transaction_Types_ID] [int] NULL,
		[Quantity] [decimal](9, 3) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL
	) ON [PRIMARY]  


    ALTER TABLE [dbo].[AS_Transaction_Details_Consignment] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transaction_Details_Consignment] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Details_Consignment_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

  
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Cash_Ups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Cash_Ups] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Cash_Ups_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Day_Ends] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Day_Ends] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Day_Ends_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Till_Payouts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Till_Payouts] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Till_Payouts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transaction_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Quotes_Sales] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    ALTER TABLE [dbo].[AS_Transactions_Address_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Address_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Address_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
   
   ALTER TABLE [dbo].[AS_Transactions_Address] ADD  
		CONSTRAINT [PK_AS_Transactions_Address_ID] PRIMARY KEY NONCLUSTERED 
		(
			[AS_Transactions_Address_ID]
		) WITH FILLFACTOR = 80

    ALTER TABLE [dbo].[AS_Transaction_Details] ADD 
    	CONSTRAINT [PK_AS_Transaction_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
 
  
    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Customer_Sales_Search] ON [dbo].[AS_Enterprise_Customer_Sales]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_GP_Search] ON [dbo].[AS_Enterprise_GP]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_Search] ON [dbo].[AS_Enterprise_Sales]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_All_Search] ON [dbo].[AS_Enterprise_Sales_All]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Sales_Order_Details] ON [dbo].[AS_Sales_Order_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transaction_Details] ON [dbo].[AS_Transaction_Details]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transactions] ON [dbo].[AS_Transactions]([AC_Customers_ID], [AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Day_Ends_Key] ON [dbo].[AS_Day_Ends]([Day_End] DESC ) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Enterprise_Customer_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Customer_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Customer_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_GP] ADD 
    	CONSTRAINT [PK_AS_Enterprise_GP] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_GP_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales_All] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales_All] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_All_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Sales_Order_Details] ADD 
    	CONSTRAINT [PK_AS_Sales_Order_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Sales_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Sales_Order_Details_AP_Products_ID] ON [dbo].[AS_Sales_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transaction_Details_AP_Products_ID] ON [dbo].[AS_Transaction_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_PaymentsTranID] ON [dbo].[AS_Transaction_Payments]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_TranSourcesTranID] ON [dbo].[AS_Transaction_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [PK_AS_Transactions] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transactions_Date_Captured] ON [dbo].[AS_Transactions]([Date_Captured]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transactions_Transaction_Type] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transactions_Comment] ON [dbo].[AS_Transactions]([Comment]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_ActiveJobSalesOrders] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_AS_Transaction_Date_Type] ON [dbo].[AS_Transactions]([Transaction_Date], [Sys_AW_Transaction_Types_ID], [AW_User_Companies_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_CBilling_Tran_ID] ON [dbo].[AS_Transactions_CBilling]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] ADD 
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_acc] DEFAULT ('SPIRAL') FOR [drs_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_gls_acc] DEFAULT ('N/A') FOR [gls_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_sys_code] DEFAULT ('SPI') FOR [sys_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_updated] DEFAULT ('no') FOR [updated],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_interfaced] DEFAULT ('no') FOR [interfaced],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_area] DEFAULT ('N/A') FOR [area],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_acct_type] DEFAULT ('N/A') FOR [acct_type],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_trs_code] DEFAULT ('100') FOR [drs_trs_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_vat_exempt_member] DEFAULT ('no') FOR [vat_exempt_member],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_rep_call_status] DEFAULT ('no') FOR [rep_call_status],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log01] DEFAULT ('no') FOR [zz_log01],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log02] DEFAULT ('no') FOR [zz_log02],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log03] DEFAULT ('no') FOR [zz_log03],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log04] DEFAULT ('no') FOR [zz_log04],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log05] DEFAULT ('no') FOR [zz_log05],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log06] DEFAULT ('no') FOR [zz_log06],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log07] DEFAULT ('no') FOR [zz_log07],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_dumped] DEFAULT ('no') FOR [dumped],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_status_ind] DEFAULT ('NE') FOR [status_ind],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_database_id] DEFAULT ('SPIRAL') FOR [database_id]

    
     CREATE  INDEX [IX_SourceTranID] ON [dbo].[AS_Transactions_Transactions]([Source_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_DestinationTranID] ON [dbo].[AS_Transactions_Transactions]([Destination_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_Xref_Tran_ID] ON [dbo].[AS_Transactions_Xref]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
     CREATE  INDEX [IX_Xref_Source_Tran_ID] ON [dbo].[AS_Transactions_Xref_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

	 CREATE  INDEX [IX_AS_Transactions_ID] ON [dbo].[AS_Transactions_Address]([AS_Transactions_ID]) WITH FILLFACTOR = 80

	 CREATE  INDEX [IX_AC_Customers_ID] ON [dbo].[AS_Transactions_Address_Detail]([AC_Customers_ID]) WITH FILLFACTOR = 80

	 CREATE  INDEX [IX_AS_Transaction_Details_Consignment_AS_Transaction_Details_ID] ON [dbo].[AS_Transaction_Details_Consignment] ([AS_Transaction_Details_ID]) WITH FILLFACTOR = 80

    setuser
    --Defaults AP_Promotion_Products
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'    
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AP_Promotions
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'

    setuser

    
    setuser
	--Defaults AS_Cash_Ups    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Cash_Ups].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Cash_Ups].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Cash_Ups].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AS_Day_Ends    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Day_Ends].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Day_Ends].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Day_Ends].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Day_Ends].[Slu_AW_Active_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Day_Ends].[AB_Transaction_Ref]'
    
    setuser

    
    setuser
	--Defaults AS_Enterprise_GP        
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_GP].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[Total]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalCost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalSales]'

    setuser

    
    setuser
	--Defaults AS_Enterprise_Sales            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales].[Pack_Size]'
    
    setuser

    
    setuser
    --Defaults AS_Enterprise_Sales_All            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales_All].[Pack_Size]'

    setuser

    
    setuser
	--Defaults AS_Sales_Order_Details
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Sales_Order_Details].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Sales_Order_Details].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Sales_Order_Details].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Sales_Order_Details].[Slu_AW_Active_ID]'

	    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Amount]'
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Discount_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Extended_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Original_Price]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Shipping_Cost]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Rate]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Till_Payouts
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Till_Payouts].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Till_Payouts].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Till_Payouts].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Till_Payouts].[Slu_AW_Active_ID]'
	
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Till_Payouts].[Amount]'
   
    setuser

    
    setuser
	--Defaults AS_Transaction_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Details].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Commission_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Discount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Quantity]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Payments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Payments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Payments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Payments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Payments].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Payments].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transaction_Payments].[Slu_AS_Card_Institutions_ID]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Sources        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Sources].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Sources].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Sources].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions  
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions].[AW_User_Companies_ID]'
	 
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions].[Slu_AW_Active_ID]'   
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Cashiers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Reps_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Tills_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Stores_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Workstations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Payment_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_CBilling].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling].[Slu_AW_Active_ID]'
	

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Authorization_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Chassis_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Client_ID_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Customer_Number]'    
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Engine_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Item_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Claim_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Fail_Reasons_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Make]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Manufacturer_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model_Year]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Network_Identity_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Odometer_Reading]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Original_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Registration_No]'
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Transaction_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Xmit_File]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling_Temp
	EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AS_Transactions_CBilling_Temp].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling_Temp].[User_ID]'
		    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling_Temp].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling_Temp].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[drs_age_month]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[trs_type]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Transactions
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Transactions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Transactions].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Transactions].[Amount]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Xref
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Xref].[AW_YesNo_Checked_ID]'

    setuser

    
    setuser
	--Defaults AS_Transactions_Xref_Sources
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref_Sources].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref_Sources].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref_Sources].[Slu_AW_Active_ID]'
    
    setuser


    setuser
	--Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address].[AW_User_Companies_ID]'
           
    setuser    


    setuser
    --Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address_Detail].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address_Detail].[AW_User_Companies_ID]'
           
          
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Address]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Suburb]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Post_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Customer_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Tax_Number]'
    
    setuser

	setuser
    --Defaults AS_Transaction_Details_Consignment  
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details_Consignment].[Quantity]'

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Details_Consignment].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Details_Consignment].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Details_Consignment].[AW_User_Companies_ID]'
	
	setuser

    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] ADD 
    	CONSTRAINT [FK_AS_Payments_Lup_AW_Payment_Methods] FOREIGN KEY 
    	(
    		[Sys_AW_Payment_Methods_ID]
    	) REFERENCES [dbo].[Sys_AW_Payment_Methods] (
    		[Sys_AW_Payment_Methods_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [FK_AS_Transactions_AW_Comments] FOREIGN KEY 
    	(
    		[AW_Comments_ID]
    	) REFERENCES [dbo].[AW_Comments] (
    		[AW_Comments_ID]
    	) NOT FOR REPLICATION ,
    	CONSTRAINT [FK_AS_Transactions_Lup_AS_Tills] FOREIGN KEY 
    	(
    		[Lup_AS_Tills_ID]
    	) REFERENCES [dbo].[Lup_AS_Tills] (
    		[Lup_AS_Tills_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Stores] FOREIGN KEY 
    	(
    		[Lup_AW_Stores_ID]
    	) REFERENCES [dbo].[Lup_AW_Stores] (
    		[Lup_AW_Stores_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Workstations] FOREIGN KEY 
    	(
    		[Lup_AW_Workstations_ID]
    	) REFERENCES [dbo].[Lup_AW_Workstations] (
    		[Lup_AW_Workstations_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Sys_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    
    Alter Table [dbo].[AS_Transactions] nocheck constraint [FK_AS_Transactions_AW_Comments]

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9910]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9910]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9910
--Purpose       :Wipe all SUPPLIER Account Balances & Transaction tables
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9910]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN

    UPDATE AO_Suppliers
    SET Account_Balance = 0,
        Current_Balance = 0,
        Days_30 = 0,
        Days_60 = 0,
        Days_90 = 0,
        Days_120 = 0,
        Days_150 = 0,
        Days_180 = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AO_Order_Items_AO_Orders]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AO_Order_Details] DROP CONSTRAINT FK_AO_Order_Items_AO_Orders

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Supplier_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Supplier_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Orders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Orders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittance_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittance_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittances_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittances_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Contracts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Contracts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Product_Discounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Product_Discounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Transactions]

    
    CREATE TABLE [dbo].[AO_Enterprise_Ageing_Temp] (
    	[AO_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Name] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Enterprise_Supplier_Ageing] (
    	[AO_Enterprise_Supplier_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SuppNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV] (
    	[AO_GRV_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Orders_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[Delivery_Note_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_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,
    	[AO_GRV_ID_Consignment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV_Details] (
    	[AO_GRV_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_GRV_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Qty] [decimal](12, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [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 ,
    	[AO_GRV_Details_ID_Consignment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Qty_Returned] [decimal](12, 3) NULL ,
    	[Qty_Sold] [decimal](12, 3) NULL ,
    	[Qty_Left] [decimal](12, 3) NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Candidates] (
    	[AO_Order_Candidates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Ready] [bit] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Reviews] [int] NULL ,
    	[Originator] [int] NULL ,
    	[AW_Remote_Access_ID] [int] 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]

    
    CREATE TABLE [dbo].[AO_Order_Candidates_Temp] (
    	[AO_Order_Candidates_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Item] [bit] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Selling] [money] NULL ,
    	[Trade_Discount] [money] NULL ,
    	[Cost] AS (round(([Selling] - [Selling] * [Trade_Discount] / 100),2)) ,
    	[Total_Cost] AS (round(([Order_Qty] * ([Selling] - [Selling] * [Trade_Discount] / 100)),2)) ,
    	[Last_Cost] [money] NULL ,
    	[Outstanding_Order_Qty] [decimal](9, 3) NULL ,
    	[Pending_Order_Qty] [decimal](9, 3) NULL ,
    	[Last_Order_Date] [datetime] NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Details] (
    	[AO_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Orders_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lead_Time] [smallint] NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Free_Qty] [decimal](9, 3) NULL ,
    	[Back_Order_Qty] [decimal](9, 3) NULL ,
    	[Receipt_Date] [datetime] NULL ,
    	[Received_Qty] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Formula_ID] [smallint] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Trade_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Rebate_Formula_ID] [smallint] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Other_Discount_Formula_ID] [smallint] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Other_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [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]

    
    CREATE TABLE [dbo].[AO_Orders] (
    	[AO_Orders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Version] [tinyint] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Rep] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Ordered] [datetime] NULL ,
    	[Confirmation] [tinyint] NULL ,
    	[Confirmation_Date] [datetime] NULL ,
    	[Our_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Total] [money] NULL ,
    	[Admin_Fee] [money] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Tax_Total] [money] NULL ,
    	[Order_Total] [money] NULL ,
    	[Sys_AO_Delivery_Methods_ID] [int] NULL ,
    	[Send_To_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr1] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr2] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr3] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Postal_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Complete] [bit] 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]

    
    CREATE TABLE [dbo].[AO_Remittance_Details_Temp] (
    	[AO_Remittance_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Remittances_Temp_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Remittances_Temp] (
    	[AO_Remittances_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Limit] [money] NULL ,
    	[Credit_Terms] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Settlement_Discount] [decimal](7, 2) NULL ,
    	[Supplier_Contact] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Telephone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Cellphone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Fax] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[To_Be_Paid_Total] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statement_Details] (
    	[AO_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Statements_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statements] (
    	[AO_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Contracts] (
    	[AO_Supplier_Contracts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Packs_Contract_Price] [money] NULL ,
    	[Packs_Contract_Qty] [decimal](6, 3) NULL ,
    	[Packs_Purchased] [decimal](6, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Product_Discounts] (
    	[AO_Supplier_Product_Discounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lup_AO_Discount_Types_ID] [int] 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]

    
    CREATE TABLE [dbo].[AO_Transaction_Payments] (
    	[AO_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions] (
    	[AO_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [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]

    
    CREATE TABLE [dbo].[AO_Transactions_Log] (
    	[AO_Transactions_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Posted_Month_ID] [tinyint] NULL ,
    	[Posted_Year_ID] [int] NULL ,
    	[Current_Month_ID] [tinyint] NULL ,
    	[Current_Year_ID] [int] NULL ,
    	[LastME_Month_ID] [tinyint] NULL ,
    	[LastME_Year_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions_Transactions] (
    	[AO_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AO_Transactions_ID] [int] NULL ,
    	[Destination_AO_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_GRV] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_GRV_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Orders] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Orders] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Orders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Contracts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Supplier_Contracts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Contracts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Product_Discounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Supplier_Discounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Product_Discounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transaction_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transactions_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Ageing_Temp] ON [dbo].[AO_Enterprise_Ageing_Temp]([Filter], [Supplier_Name], [Supplier_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Supplier_Ageing] ON [dbo].[AO_Enterprise_Supplier_Ageing]([Filter], [Supplier], [SuppNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_Order_Items_Orders_ID] ON [dbo].[AO_Order_Details]([AO_Orders_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittance_Details_Temp] ON [dbo].[AO_Remittance_Details_Temp]([AO_Remittance_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittances_Temp] ON [dbo].[AO_Remittances_Temp]([AO_Remittances_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statement_Details] ON [dbo].[AO_Statement_Details]([AO_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statements] ON [dbo].[AO_Statements]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Enterprise_Supplier_Ageing] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Supplier_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Supplier_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_GRV_AW_Transaction_Types_ID] ON [dbo].[AO_GRV]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_AP_Products_ID] ON [dbo].[AO_Order_Candidates]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_Temp_AP_Products_ID] ON [dbo].[AO_Order_Candidates_Temp]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [PK_Order_Items] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_Order_Items_AP_Products_ID] ON [dbo].[AO_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Orders_AO_Suppliers_ID] ON [dbo].[AO_Orders]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Open_Orders] ON [dbo].[AO_Orders]([Date_Ordered], [Complete]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statement_Details_Key] ON [dbo].[AO_Statement_Details]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statements_Key] ON [dbo].[AO_Statements]([AW_Period_Procedures_ID], [FullName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Products_ID] ON [dbo].[AO_Supplier_Contracts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Suppliers_ID] ON [dbo].[AO_Supplier_Contracts]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Product_Discounts_AP_Products_ID] ON [dbo].[AO_Supplier_Product_Discounts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Transactions_AO_GRV_ID] ON [dbo].[AO_Transactions]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[180+Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Enterprise_Supplier_Ageing].[CompanyID]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV].[User_ID]'

    
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV].[AO_GRV_ID_Consignment]'
	
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV_Details].[User_ID]'
   
   
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_GRV_Details].[AO_GRV_Details_ID_Consignment]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Returned]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Sold]'


	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty_Left]'
    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Order_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Originator]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Ready]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Reviews]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Candidates].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates_Temp].[AW_User_Companies_ID]'

    --Computed
    --EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates_Temp].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Order_Candidates_Temp].[Notes]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Outstanding_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Pending_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Selling]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[Service_Level]'

    --Computed
	--EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Trade_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates_Temp].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Back_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Free_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Lead_Time]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Other_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Rebate_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Received_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Trade_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Details].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Admin_Fee]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AW_Remote_Access_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Orders].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Complete]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Confirmation]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Orders].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Invoice_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Order_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Orders].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Tax_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Orders].[User_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Version]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Remittances_Temp].[Date_Captured]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Statements].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Contracts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Contracts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Purchased]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Contracts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Contracts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Product_Discounts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Product_Discounts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Product_Discounts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Product_Discounts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transaction_Payments].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transaction_Payments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transaction_Payments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transaction_Payments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transaction_Payments].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transaction_Payments].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Payment_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Remittance_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Settlement_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Log].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Log].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transactions_Transactions].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions_Transactions].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [FK_AO_Order_Items_AO_Orders] FOREIGN KEY 
    	(
    		[AO_Orders_ID]
    	) REFERENCES [dbo].[AO_Orders] (
    		[AO_Orders_ID]
    	)

    
    ALTER TABLE [dbo].[AO_Transactions] ADD 
    	CONSTRAINT [FK_AO_Purchase_Transactions_Lup_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9920]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9920]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9920
--Purpose       :Wipe all GENERAL LEDGER Transaction tables
--              :
--Parameters    :
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--AW_Company_Banks Not cleared
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

CREATE PROCEDURE [dbo].[sp_AW_9920]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    --------------------------------------------------------------------------------
    --Clear GL Account Balances

    UPDATE AB_Accounts
    SET AB_Account_Balance = 0,
        Opening_Balance = 0,
        Opening_Date = NULL,
        Opening_Month = 0,
        Opening_Year = 0
    --------------------------------------------------------------------------------
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Journals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Journals

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Recurring]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Recurring

    
    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]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Batches]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Batches]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Notes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Notes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Inflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Inflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Outflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Outflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Balance_Sheet]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Income_Statement]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Management_Accounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Trial_Balance]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journal_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journal_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring_Details]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures_Deleted]

    
    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]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Batches] (
    	[AB_Cash_Book_Batches_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Split_Amount] [money] NULL ,
    	[VAT_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail] (
    	[AB_Cash_Book_IBS_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Post_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] (
    	[AB_Cash_Book_IBS_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[AB_Cash_Book_IBS_Detail_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Header] (
    	[AB_Cash_Book_IBS_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Banks_ID] [smallint] NOT NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Start_Date] [datetime] NOT NULL ,
    	[End_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Auto_Recon] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map] (
    	[AB_Cash_Book_IBS_Map_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Map_1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_3] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] (
    	[AB_Cash_Book_IBS_Map_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[AB_Cash_Book_IBS_Map_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Notes] (
    	[AB_Cash_Book_IBS_Notes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Note] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transaction_Details] (
    	[AB_Cash_Book_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transactions] (
    	[AB_Cash_Book_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Reference_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Recon_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL ,
    	[StartDate] [datetime] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Inflow_Projections] (
    	[AB_Cash_Inflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Inflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Outflow_Projections] (
    	[AB_Cash_Outflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Outflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
    	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_B1_ID] [int] NULL ,
    	[Sys_AB_B2_ID] [int] NULL ,
    	[Sys_AB_B3_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
    	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[TCRUST] [money] NULL ,
    	[TCSTEEL] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
    	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Sys_AB_I5_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level5] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
    	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Divisions] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Groups] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_GL_Transactions] (
    	[AB_GL_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[AB_Transaction_Date] [datetime] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Transaction_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]

    
    CREATE TABLE [dbo].[AB_Journal_Details] (
    	[AB_Journal_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journals] (
    	[AB_Journals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Journal_Date] [datetime] NULL ,
    	[Journal_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Journal_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] 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]

    
    CREATE TABLE [dbo].[AB_Recurring] (
    	[AB_Recurring_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Recurring_Date] [datetime] NULL ,
    	[Recurring_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Recurring_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] 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]

    
    CREATE TABLE [dbo].[AB_Recurring_Details] (
    	[AB_Recurring_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Recurring_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]


	CREATE TABLE [dbo].[AW_Period_Procedures](
		[AW_Period_Procedures_ID] [int] IDENTITY(1,1) NOT NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Month] [tinyint] NULL,
		[Year] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [smalldatetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY]		


	CREATE TABLE [dbo].[AW_Period_Procedures_Deleted](
		[AW_Period_Procedures_Deleted_ID] [int] IDENTITY(1,1) NOT NULL,
		[AW_Period_Procedures_ID] [int] NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) NULL,
		[Month_ID] [tinyint] NULL,
		[Year_ID] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL
	) ON [PRIMARY]		
		
		
	ALTER TABLE [dbo].[AW_Period_Procedures_Deleted] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures_Deleted] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_Deleted_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

			
    ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_ID]
    	) WITH  FILLFACTOR = 90  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] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Batches] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Batches] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Batches_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Notes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Notes] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Notes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transaction_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Inflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Inflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Inflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Outflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Outflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Outflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Balance_Sheet_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Income_Statement_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Management_Accounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Trial_Balance_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_GL_Transactions_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journal_Details_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journals_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([N1], [RowTypeID], [Description]) ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail]([Transaction_Date], [Bank_Description], [Amount], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail_Splits]([AB_Cash_Book_IBS_Header_ID], [AB_Cash_Book_IBS_Detail_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AB_Cash_Book_IBS_Map_Splits] ON [dbo].[AB_Cash_Book_IBS_Map_Splits]([AW_Company_Banks_ID], [AB_Cash_Book_IBS_Map_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([AB_Cash_Flow_Forecast_Temp_ID]) ON [PRIMARY]

    
    setuser
   
    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_User_ID]', N'[AB_Budgets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Batches].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Batches].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Split_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[VAT_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Batches].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Batches].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Batches].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Batches].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Amount]'
            
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Comments]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Post_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Ref_No]'    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail].[Sys_AW_Tax_Methods_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Transaction_Date]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail].[User_ID]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail].[AW_User_Companies_ID]'  
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail_Splits].[AB_Accounts_ID]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Tax_Amount]'  

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail_Splits].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail_Splits].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail_Splits].[AW_User_Companies_ID]'  
	 
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail_Splits].[Slu_AW_Active_ID]'   
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Auto_Recon]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[End_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Posting_Type]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Start_Date]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Header].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Header].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Comments]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map_Splits].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map_Splits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map_Splits].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Notes].[Note]'

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Notes].[Date_Captured]' 
	   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Notes].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Notes].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'
	
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Transactions].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Transactions].[Slu_AW_Years_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Inflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Inflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Inflow_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Inflow_Projections].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Inflow_Projections].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Inflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Outflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Outflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Outflow_Date]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Outflow_Projections].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Outflow_Projections].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Outflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Ref]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'   
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'
    
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'
    
    setuser

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions] FOREIGN KEY 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) REFERENCES [dbo].[AB_Cash_Book_Transactions] (
    		[AB_Cash_Book_Transactions_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transactions_AW_Company_Banks] FOREIGN KEY 
    	(
    		[AW_Company_Banks_ID]
    	) REFERENCES [dbo].[AW_Company_Banks] (
    		[AW_Company_Banks_ID]
    	)

    
    ALTER TABLE [dbo].[AB_GL_Transactions] ADD 
    	CONSTRAINT [FK_AB_GL_Transactions_Lup_AB_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AB_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AB_Transaction_Types] (
    		[Sys_AB_Transaction_Types_ID]
    	),
    	CONSTRAINT [FK_AB_Transactions_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Journal_Details] ADD 
    	CONSTRAINT [FK_AB_Journal_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Journal_Details_AB_Journals] FOREIGN KEY 
    	(
    		[AB_Journals_ID]
    	) REFERENCES [dbo].[AB_Journals] (
    		[AB_Journals_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Recurring_Details] ADD 
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Recurring] FOREIGN KEY 
    	(
    		[AB_Recurring_ID]
    	) REFERENCES [dbo].[AB_Recurring] (
    		[AB_Recurring_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9930]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9930]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9930
--Purpose       :Wipe all TASKS Transaction tables
--              :
--Parameters    :
--Date          :2002/02/03
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9930]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AT_Tasks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AT_Tasks]

        
        CREATE TABLE [dbo].[AT_Tasks] (
        	[AT_Tasks_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Start_Date] [datetime] NULL ,
        	[Date_Started] [datetime] NULL ,
        	[Date_Completed] [datetime] NULL ,
        	[Due_Date] [datetime] NULL ,
        	[Remind] [bit] NULL ,
        	[Actual_Work] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Task_Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Actor1_ID] [int] NULL ,
        	[Actor2_ID] [int] NULL ,
        	[User2_ID] [int] NULL ,
        	[Subject_ObjectName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Sys_AT_Subject_Type_ID] [tinyint] NULL ,
        	[Subject_ID] [int] NULL ,
        	[Sys_AT_Status_ID] [int] NULL ,
        	[Sys_AT_Notifications_ID] [tinyint] 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].[AT_Tasks] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AW_Tasks] PRIMARY KEY  CLUSTERED 
        	(
        		[AT_Tasks_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Actual_Work]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Remind]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Subject_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Subject_ObjectName]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Notifications_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Status_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Subject_Type_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Task_Message]'

        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AT_Tasks].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AT_Tasks].[User_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AT_Tasks].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AT_Tasks].[Slu_AW_Active_ID]'
        
        setuser
    
        SET @ReturnValue = 1
    
    END

RETURN @ReturnValue
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9940]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9940]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9940
--Purpose       : Wipe all PRODUCT Transaction tables
--Date          : 2002/02/11
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9940]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN
	--Average Cost Must be Zeroed or else audit trail will not make sense or balance??????
    --First wipe the Test Data
    UPDATE AP_Products 
    SET Average_Cost = 0,
		On_Hand = 0,
		Sales_Order_Reserved = 0,
		Quote_Reserved = 0,
		Job_Reserved = 0,
		Last_Sale_Date = NULL,
		Service_Level = 1,
		Min_Stock_Level = 0,
		Min_Order_Qty = 0,
		Max_Order_Qty = 0,
		Levy_AP_Product_ID = 0

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Bond_Stock_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Bond_Stock_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Slow_Moving_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Filter]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Replenish_Max]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Replenish_Max]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Valuation]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Adjustments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Valuations]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Valuations]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Product_Selling_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Product_Selling_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_History]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Inventory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Inventory]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Stock_Takes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Stock_Takes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Exchange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Exchange]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Take_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Take_Procedures]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Log]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Audit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Audit]
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Product_Bins]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Product_Bins]
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Bins]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Bins]

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Bins_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Bins_History]

    CREATE TABLE [dbo].[AP_Bond_Stock_Log] (
    	[AP_Bond_Stock_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[File_Type] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Location] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Computer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Login_URL] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_User_Name] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Password] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Folder] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Date] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Time] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Row_CNT] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] (
    	[AP_Enterprise_Slow_Moving_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock] (
    	[AP_Enterprise_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Filter] (
    	[AP_Enterprise_Stock_Filter_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] (
    	[AP_Enterprise_Stock_Replenish_Max_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Valuation] (
    	[AP_Enterprise_Stock_Valuation_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Adjustments] (
    	[AP_Inventory_Adjustments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Sys_AP_Adjustment_Types_ID] [tinyint] NULL ,
    	[Previous_Last_Cost] [money] NOT NULL ,
    	[Previous_Average_Cost] [money] NULL ,
    	[Previous_On_Hand] [decimal](9, 3) NULL ,
    	[Previous_Job_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Quote_Reserved] [decimal](9, 3) NULL ,
    	[New_Last_Cost] [money] NULL ,
    	[New_Average_Cost] [money] NULL ,
    	[New_On_Hand] [decimal](9, 3) NULL ,
    	[New_Job_Reserved] [decimal](9, 3) NULL ,
    	[New_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[New_Quote_Reserved] [decimal](9, 3) NULL ,
    	[Note] [varchar] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Valuations] (
    	[AP_Inventory_Valuations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Qty_On_Hand] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Product_Selling_Prices] (
    	[AP_Product_Selling_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Prev_Price1_Effective_Date] [datetime] NULL ,
    	[Prev_Price1_Price1] [money] NULL ,
    	[Prev_Price1_Price2] [money] NULL ,
    	[Prev_Price2_Effective_Date] [datetime] NULL ,
    	[Prev_Price2_Price1] [money] NULL ,
    	[Prev_Price2_Price2] [money] NULL ,
    	[New_Price1_Effective_Date] [datetime] NULL ,
    	[New_Price1_Price1] [money] NULL ,
    	[New_Price1_Price2] [money] NULL ,
    	[New_Price2_Effective_Date] [datetime] NULL ,
    	[New_Price2_Price1] [money] NULL ,
    	[New_Price2_Price2] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_History] (
    	[AP_Products_History_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

 
    CREATE TABLE [dbo].[AP_Products_Inventory] (
    	[AP_Products_Inventory_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NOT NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Stock_Takes] (
    	[AP_Products_Stock_Takes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Stock_Take_Procedures_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Count1] [decimal](9, 3) NULL ,
    	[Count2] [decimal](9, 3) NULL ,
    	[Count3] [decimal](9, 3) NULL ,
    	[Total_Count] [decimal](12, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Variance] [decimal](12, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Exchange] (
    	[AP_Stock_Exchange_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[On_Order] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Count_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Take_Procedures] (
    	[AP_Stock_Take_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Procedure_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[Stock_Adjustment_Total] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Details] (
    	[AP_Stock_Transfer_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [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]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Log] (
    	[AP_Stock_Transfer_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_GL_Transactions_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NOT NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[SIT_User_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[TRF_User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
	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,
		[AP_Products_ID] [int] NOT NULL,
		[Field] [varchar](50) NULL,
		[Prev_Value] [varchar](50) NULL,
		[New_Value] [varchar](50) NULL,		
		[Changes_Sent] [int] NULL,
		[User_ID] [int] NULL
	) ON [PRIMARY]

  
	CREATE TABLE [AC_Product_Bins](
		[AC_Product_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] 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] 
 
	CREATE TABLE [AP_Products_Bins](
		[AP_Products_Bins_ID] [int] IDENTITY(1,1) NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[On_Hand] [decimal](9, 3) NOT NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY] 

	CREATE TABLE [AP_Products_Bins_History](
		[AP_Products_Bins_History_ID] [int] IDENTITY(1,1) NOT NULL,
		[Batch_No] [int] NOT NULL,
		[AP_Products_ID] [int] NOT NULL,
		[From_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[From_Bin_Previous_On_Hand] [decimal](9, 3) NOT NULL,
		[From_Bin_New_On_Hand] [decimal](9, 3) NOT NULL,
		[To_Lup_AP_Product_Bins_ID] [int] NOT NULL,
		[To_Bin_Previous_On_Hand] [decimal](9, 3) NOT NULL,
		[To_Bin_New_On_Hand] [decimal](9, 3) NOT NULL,
		[Movement_Source] [varchar](10) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY] 
    
    ALTER TABLE [dbo].[AP_Bond_Stock_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Bond_Stock_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Bond_Stock_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Valuations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Valuations] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Valuations_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_History_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Inventory] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Inventory] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Inventory_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Stock_Takes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Stock_Takes] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Stock_Takes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Take_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Take_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Take_Procedures_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Transfer_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 


    ALTER TABLE [dbo].[AP_Products_Audit] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Audit] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Audit_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
    

    ALTER TABLE [dbo].[AP_Products_Bins] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Bins] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Bins_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
  

    ALTER TABLE [dbo].[AP_Products_Bins_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Bins_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Bins_History_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 


        
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter_Search] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Replenish_Max_Search] ON [dbo].[AP_Enterprise_Stock_Replenish_Max]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Product_Selling_Prices] ON [dbo].[AP_Product_Selling_Prices]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Stock_Transfer_Details] ON [dbo].[AP_Stock_Transfer_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

   
	 CREATE  CLUSTERED  INDEX [IX_AC_Product_Bins_AC_Customers_ID] ON [AC_Product_Bins]([AC_Customers_ID]) WITH FILLFACTOR = 80  ON [PRIMARY]
   
    
	 CREATE  NONCLUSTERED  INDEX [IX_AP_Products_Bins_AP_Products_ID] ON [AP_Products_Bins]([AP_Products_ID]) WITH FILLFACTOR = 80


  	 CREATE  NONCLUSTERED  INDEX [IX_AP_Products_Bins_History_AP_Products_ID] ON [AP_Products_Bins_History]([AP_Products_ID]) WITH FILLFACTOR = 80
    
    
    ALTER TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Slow_Moving_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Slow_Moving_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Filter_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Replenish_Max] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Replenish_Max_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Valuation_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Inventory_Adjustments_AP_Products_ID] ON [dbo].[AP_Inventory_Adjustments]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Product_Selling_Prices] ADD 
    	CONSTRAINT [PK_AP_Product_Selling_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Product_Selling_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_History_AP_Products_ID] ON [dbo].[AP_Products_History]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_AP_Products_Static_ID] ON [dbo].[AP_Products_Inventory]([AP_Products_Static_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_Date_Updated] ON [dbo].[AP_Products_Inventory]([Date_Updated]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Stock_Takes_AP_Products_ID] ON [dbo].[AP_Products_Stock_Takes]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Stock_Exchange_AP_Products_ID] ON [dbo].[AP_Stock_Exchange]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Details] ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Stock_Transfer_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
	CREATE  INDEX [IX_AP_Stock_Transfer_Details_AP_Products_ID] ON [dbo].[AP_Stock_Transfer_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
	CREATE  INDEX [IDX_AP_Stock_Transfer_Log_AS_Transactions_ID] ON [dbo].[AP_Stock_Transfer_Log]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

	CREATE  INDEX [IX_AP_Products_Audit_AP_Products_ID] ON [dbo].[AP_Products_Audit]([AP_Products_ID]) WITH  FILLFACTOR = 80 ON [PRIMARY]
	
	CREATE  INDEX [Ind_AP_Products_Audit_Changes_Sent] ON [dbo].[AP_Products_Audit]([Changes_Sent]) WITH  FILLFACTOR = 80 ON [PRIMARY]
    
    
    setuser     
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Computer]'        
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Location]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Time]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Folder]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Login_URL]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Password]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_User_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Row_CNT]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Bond_Stock_Log].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Bond_Stock_Log].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Bond_Stock_Log].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Slow_Moving_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Filter].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Valuation].[Pack_Size]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Sales_Order_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Average_Cost]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Sales_Order_Reserved]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Qty_On_Hand]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Valuations].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Valuations].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Valuations].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Valuations].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price2]'                
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Date_Captured]'  
      
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Product_Selling_Prices].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Product_Selling_Prices].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Product_Selling_Prices].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Average_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Qty]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Standard_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_History].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_History].[AW_User_Companies_ID]'
    
    setuser

    
    setuser            
        
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Inventory].[Date_Updated]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Inventory].[Lup_AP_Product_Locations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Inventory].[On_Hand]'    
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Inventory].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Inventory].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Inventory].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Inventory].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count3]'      
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[On_Hand]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Total_Count]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Unit_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Variance]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Stock_Takes].[Date_Captured]'
	
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Stock_Takes].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Stock_Takes].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Stock_Takes].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]' 
               
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'                
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Order]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Exchange].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'
    
    setuser

    
    setuser        
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Take_Procedures].[Stock_Valuation]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Take_Procedures].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Take_Procedures].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Take_Procedures].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Take_Procedures].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Amount]'    
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Back_Order]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Quantity]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Rate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Price]'        
	    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Details].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Details].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Details].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Transfer_Details].[Slu_AW_Active_ID]'    
	
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Amount]'               
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Log].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Log].[TRF_User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Stock_Transfer_Log].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Log].[AW_User_Companies_ID]'
    
    setuser

    
	setuser
       
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Audit].[User_ID]'
    
    setuser
       
       
    setuser    
   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Product_Bins].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Product_Bins].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Product_Bins].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Product_Bins].[Slu_AW_Active_ID]'

    setuser
    
    
    setuser    
   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Bins].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Bins].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Bins].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Bins].[Slu_AW_Active_ID]'

    setuser


    setuser    
  
	EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Products_Bins_History].[Movement_Source]'
	   
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Bins_History].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Bins_History].[User_ID]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Bins_History].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Bins_History].[Slu_AW_Active_ID]'

    setuser
        
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)
  
    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9970]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9970]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9970
--Purpose       : Wipe all FACTORY Transaction tables
--Date          : 2011/05/15 (2004.5.1)
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9970]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

    BEGIN
    
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets]    

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets_Deleted]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills_Deleted]

        
        CREATE TABLE [dbo].[AF_Job_Tickets] (
        	[AF_Job_Tickets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Post] [bit] NULL ,
        	[Job_No] [int] NULL ,
        	[Job_Date] [datetime] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[Order_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
        	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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 ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
        
        CREATE TABLE [dbo].[AF_Waybills] (
        	[AF_Waybills_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Waybill_Date] [datetime] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
   
	CREATE TABLE [dbo].[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) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[AP_Products_ID] [int] NULL,
		[Lup_AP_Product_Manufacturers_ID] [int] NULL,
		[Serial_No] [varchar](13) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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) COLLATE SQL_Latin1_General_CP1_CI_AS 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
	) ON [PRIMARY]

	CREATE TABLE [dbo].[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
	) ON [PRIMARY]


        ALTER TABLE [dbo].[AF_Job_Tickets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Job_Tickets] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Job_Tickets_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
        ALTER TABLE [dbo].[AF_Waybills] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Waybills] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Waybills_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Factory_ID] ON [dbo].[AF_Job_Tickets]([AO_Suppliers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Job_No] ON [dbo].[AF_Job_Tickets]([Job_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Customer_ID] ON [dbo].[AF_Job_Tickets]([AC_Customers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Waybill_No] ON [dbo].[AF_Job_Tickets]([AF_Waybills_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Invoice_No] ON [dbo].[AF_Job_Tickets]([Invoice_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Billing_No] ON [dbo].[AF_Job_Tickets]([Billing_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_GRV_ID] ON [dbo].[AF_Job_Tickets]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Product_ID] ON [dbo].[AF_Job_Tickets]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_AS_Transactions_ID] ON [dbo].[AF_Job_Tickets]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Waybills_AO_Suppliers_ID] ON [dbo].[AF_Waybills]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AF_Job_Tickets].[Lup_AP_Fail_Reasons_ID]'    
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AF_Job_Tickets].[Post]'
    
		EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Job_Tickets].[Date_Captured]'
		
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Job_Tickets].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Job_Tickets].[Slu_AW_Active_ID]'
            
        setuser
    
        
        setuser    
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Waybills].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AF_Waybills].[User_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Waybills].[AW_User_Companies_ID]'
        
		EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Waybills].[Slu_AW_Active_ID]'
        
        setuser
    
        
        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9950]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9950]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9950
--Purpose       : Clear all System Transaction Number tables
--              :
--Parameters    :
--Date          : 2002/02/11
--Authors       : TB
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9950]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = 0

    UPDATE Sys_AW_Transaction_Numbers
    SET Last_Number = 0

    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9980]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9980]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9980
--Purpose       :RE-LINK PRODUCTS & SUPPLIERS (AP_Products_Suppliers)
--              :
--Parameters    :
--Date          :2002/08/02
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AW_9980]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Suppliers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Products_Suppliers]

        
        CREATE TABLE [dbo].[AP_Products_Suppliers] (
        	[AP_Products_Suppliers_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Lead_Time] [smallint] NULL ,
        	[Trade_Disc_Perc] [decimal](5, 2) NULL ,
        	[Trade_Disc_Date] [datetime] NULL ,
        	[Start_Date] [datetime] NULL ,
        	[AW_Trade_Discount_Formula_ID] [smallint] NULL ,
        	[AW_Rebate_Discount_Formula_ID] [smallint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [int] NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AP_Products_Suppliers_AP_Products_ID] ON [dbo].[AP_Products_Suppliers]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Products_Suppliers] ADD 
        	CONSTRAINT [PK_AP_Products_Suppliers] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Products_Suppliers_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
         CREATE  INDEX [IX_AP_Products_Suppliers_AO_Suppliers_ID] ON [dbo].[AP_Products_Suppliers]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Rebate_Discount_Formula_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Trade_Discount_Formula_ID]'
                                   
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[Lead_Time]'
                       
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Suppliers].[Trade_Disc_Perc]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Suppliers].[Date_Captured]'
        
		EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Suppliers].[User_ID]'
		
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Suppliers].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Suppliers].[Slu_AW_Active_ID]'        
        
        setuser
    
    
        ------------------------------------------------------------------------------------
        --INSERT AP_Products_Suppliers
        ------------------------------------------------------------------------------------
        INSERT AP_Products_Suppliers
            (
        	AP_Products_ID,
        	AO_Suppliers_ID,
        --	Lead_Time,    --IS NOW A DEFAULT OF 1
        	Start_Date
            )
        SELECT
            ap_products_id,
            Default_Supplier_ID,
        --  1,
            getdate()
        FROM ap_products
        WHERE Default_Supplier_ID IS NOT NULL


        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF
GO
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS
--Purpose       :Get Sales Submission Data For Rewards Program
--Parameters    :
--Date          :2014-10-15
--Authors       :RL
--Version       :6.0
--MODS          :
--V6.3 RL 2017-05-16	:Changed layout for Isabel from Cubu Consulting
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	DECLARE @LastDayEnd				DateTime,
			@Temp_No_Days			Varchar(20),	
			@No_Days				Int,
			@OLD_Transaction_Number	Varchar(20),
			@sql					Varchar(8000),
			@Store_Name				Varchar(100),

			@Transaction_Number		Varchar(20),
			@Customer				Varchar(100),
			@Vehicle_Reg			Varchar(20),
			@Contact_Number			Varchar(20),
			@Email_Address			Varchar(100),
			@Transaction_Date		Varchar(10),
			@Product_Description	Varchar(50),
			@Quantity				Varchar(20),
			@Selling_Price			Varchar(20)
			
			--@Group					Varchar(20),
			--@Market_Position		Varchar(20),
			--@Store					Varchar(50),
			--@
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	SELECT @Store_Name = Replace(ISNULL(Company_Trading_Name,Company_Name),',','')
	FROM AW_User_Companies    
     
    SET @OLD_Transaction_Number = '' 
                      	
   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 GETDATE() < '2017-05-31'
		SET @No_Days = 30
			
	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
	
	SET @sql = '        DECLARE Get_Data CURSOR FOR '
	
	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + '		ISNULL(t.Transaction_Number,''''), '

	SET @sql = @sql + '		CASE WHEN ISNULL(ad.Customer_Name,'''') = '''' '
	SET @sql = @sql + '		THEN '
	SET @sql = @sql + '		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
	SET @sql = @sql + '		THEN '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(c.surname,''''))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', '''')  ' 
	SET @sql = @sql + '		ELSE '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(c.surname,''''))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', '''') + '' ''+' + ' '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(c.Firstnames,''''))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', '''') '  	
	SET @sql = @sql + '		END '
	SET @sql = @sql + '		ELSE '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(ad.Customer_Name,''''))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', '''')  ' 
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(s.Reg_No,ISNULL(t.Comment,'''')))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', ''''), '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(c.Home_Tel_No,ISNULL(c.Cell_No,'''')))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', ''''), '
	SET @sql = @sql + '		REPLACE(REPLACE(REPLACE( LTRIM(RTRIM(ISNULL(c.Home_Email,ISNULL(c.Orders_URL,'''')))),' + ''',''' + ','' '') ,' + '''''' + ','' ''), ' + '''' + '"' + '''' + ', ''''), '

	SET @sql = @sql + '		CONVERT(Varchar(10),t.Transaction_Date,103), '
	SET @sql = @sql + '		ISNULL(p.[Description],''''), '
	SET @sql = @sql + '		CONVERT(Varchar(20),ISNULL(d.Quantity,0)), '
	SET @sql = @sql + '		CONVERT(Varchar(20), (ISNULL(d.Extended_Amount,0) - ISNULL(d.Tax_Amount,0)) ) '

	SET @sql = @sql + '		FROM ' 
	SET @sql = @sql + '		AS_Transactions t '
	SET @sql = @sql + '		INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '
	
	SET @sql = @sql + '		LEFT OUTER JOIN AC_Customers c '
	SET @sql = @sql + '			ON t.AC_Customers_ID = c.AC_Customers_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AS_Transactions_Address a '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = a.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AS_Transactions_Address_Detail ad '
	SET @sql = @sql + '			ON a.AS_Transactions_Address_Detail_ID = ad.AS_Transactions_Address_Detail_ID '
	
	SET @sql = @sql + '		LEFT OUTER JOIN AC_Assets s '
	SET @sql = @sql + '			ON s.AS_Transactions_ID = t.AS_Transactions_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 + '		INNER 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 + '		INNER 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 + '		INNER 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 + '	WHERE ' 
	SET @sql = @sql + '		(t.Sys_AW_Transaction_Types_ID = 3  OR '      -- Invoices
	SET @sql = @sql + '		 t.Sys_AW_Transaction_Types_ID = 4)  AND '    -- Refunds	
	SET @sql = @sql + '     t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   			
	SET @sql = @sql + '		t.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		t.Total_Amount <> 0 AND '
	SET @sql = @sql + '		p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'	
    SET @sql = @sql + '		t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '		t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '		

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
	SET @sql = @sql + '	ORDER BY t.Transaction_Date, t.Transaction_Number ' 	  	
--Select @sql
	Exec (@sql)
	
	OPEN Get_Data
	
	FETCH NEXT FROM Get_Data INTO @Transaction_Number, @Customer, @Vehicle_Reg, @Contact_Number, @Email_Address,
							@Transaction_Date, @Product_Description, @Quantity, @Selling_Price

	--Insert Header Sales Records
	INSERT INTO @Tbl_F
	(
		[Rec]
	)
	VALUES
	(
		'Group' + ',' +
		'Market Position' + ',' +
		'Store' + ',' +
		'Transmission Source' + ',' +
		'Invoice Number' + ',' +
		'Customer Name' + ',' +
		'Vehicle Registration' + ',' +
		'Contact Number' + ',' +
		'Email Address' + ',' +
		'Date Of Sale' + ',' +
		'Tyre Description' + ',' +
		'Tyre Quantity' + ',' +
		'Tyre Selling Price'
		
	)

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SELECT @Product_Description = Replace(@Product_Description,',',' ')						
	
	
		--Insert Header Sales Records
		INSERT INTO @Tbl_F
		(
			[Rec]
		)
		VALUES
		(
			'Goodyear South Africa' + ',' +
			'Hi-Q' + ',' +
			@Store_Name + ',' +
			'Spiralsoft'  + ',' +
			@Transaction_Number + ',' +
			@Customer + ',' +
			@Vehicle_Reg + ',' +
			@Contact_Number + ',' +
			@Email_Address + ',' +
			REPLACE(@Transaction_Date,'/','') + ',' +
			@Product_Description + ',' +
			@Quantity + ',' +
			@Selling_Price			
		)
			
	FETCH NEXT FROM Get_Data INTO @Transaction_Number, @Customer, @Vehicle_Reg, @Contact_Number, @Email_Address,
							@Transaction_Date, @Product_Description, @Quantity, @Selling_Price
	END	
	CLOSE Get_Data
	Deallocate Get_Data

	SELECT [Rec] FROM @Tbl_F

SET NOCOUNT OFF
GO
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]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
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),
			@sql					Varchar(8000)
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	--SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') FROM AW_User_Companies
     
    SET @OLD_Transaction_Number = '' 
                      	
   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
			
	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
	
	SET @sql = '        DECLARE Get_Data CURSOR FOR '
	SET @sql = @sql + '	SELECT '
	SET @sql = @sql + '		CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '		WHEN 3 THEN ''' + 'IN' +  ''' '
	SET @sql = @sql + '		WHEN 4 THEN ''' + 'CN' +  ''' '
	SET @sql = @sql + '		ELSE ''' + 'UN' +  ''' '
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(t.Transaction_Number,''''), '					--Transaction Number
	SET @sql = @sql + '		CONVERT(Varchar(10),t.Transaction_Date,112), '		--Transaction Date
	SET @sql = @sql + '		CONVERT(Varchar(5),t.Transaction_Date,108), '			--Transaction Time
	SET @sql = @sql + '		CONVERT(VARCHAR(20),IsNull(t.Lup_AS_Reps_ID,0)), '	--Transaction Rep ID
	SET @sql = @sql + '		CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '		WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '     
	SET @sql = @sql + '		ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(p.Product_Code,''''), '							--Product Code
	SET @sql = @sql + '		ISNULL(p.[Description],''''), '							--Product Description
	SET @sql = @sql + '		CONVERT(Varchar(20),ISNULL(d.Quantity,0)) '			--Quantity
	SET @sql = @sql + '		FROM ' 
	SET @sql = @sql + '		AS_Transactions t '
	SET @sql = @sql + '		INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '			ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_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 + '		INNER 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 + '		INNER 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 + '		INNER 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 + '	WHERE ' 
	SET @sql = @sql + '		(t.Sys_AW_Transaction_Types_ID = 3  OR '      -- Invoices
	SET @sql = @sql + '		 t.Sys_AW_Transaction_Types_ID = 4)  AND '    -- Refunds	
	SET @sql = @sql + '     t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   			
	SET @sql = @sql + '		t.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		t.Total_Amount <> 0 AND '
	SET @sql = @sql + '		p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'	
    SET @sql = @sql + '		t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '		t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '		

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
	SET @sql = @sql + '	ORDER BY t.Transaction_Date ' 	  	
--	Select @sql
	Exec (@sql)
	
	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
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS_SEL
--Purpose       :Select Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	c.Surname AS [Customer Name] '	
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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 + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW_SEL
--Purpose       :Select Sales Submission Data For Rewards
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '	WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '   
	SET @sql = @sql + '	ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '	END As [Sales Rep]'
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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_AS_Reps r '
	SET @sql = @sql + '		ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export	
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO
--Insert chkSaveMenuConsignmentNote - Used for Saveing Consignment Notes
--chkSaveMenuConsignmentNote
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkSaveMenuConsignmentNote'
	AND Control_Index = 0
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkSaveMenuConsignmentNote',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--Insert chkEnableCurrencySymbol - Used for printing currency symbol on documents
--chkEnableCurrencySymbol
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkEnableCurrencySymbol'
	AND Control_Index = 0
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkEnableCurrencySymbol',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO

IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtPrintCurrencySymbol'
	AND Control_Index = 0
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtPrintCurrencySymbol',
		0,
		'',
		Getdate(),
		1,
		1
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Stock_Transfer_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Stock_Transfer_Products]
GO
SET ANSI_NULLS ON

GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Products
--Purpose       :NEW sp_AP_Select_Stock_Transfer_Products select products for stock transfer
--				 sp_AS_POS_Products_Select was old proc used, but needed to change to new 
--				 to accommodate product bins
--Date          :2016/10/03
--Authors       :RL
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint

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

        	SELECT 
        		p.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [ConsignmentStock],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  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.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Qty],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID 
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  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.AP_Products_ID as [ID],        	
        		p.Description, 
        		ISNULL(p.Product_Code, '') as [Code], 
        		p.On_Hand AS [Total On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        		
                pb.Description AS [Bin],
                b.On_Hand as [Qty On Hand], --XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Qty],
				--Job_Reserved AS [Job Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Job_Reserved(p.AP_Products_ID)) as [Job Res], 
				--Sales_Order_Reserved AS [S/O Reserved],
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) as [S/O Res], 
				--Quote_Reserved AS [Quote Reserved]
				CONVERT(decimal(9, 3), dbo.fn_AP_Products_Quoted(p.AP_Products_ID)) as [Quote Res],
        		dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
        		p.Average_Cost AS [Avg Cost], 
        		p.Last_Cost AS [Last Cost], 
        		p.Pack_Size AS [Qty],
        		p.Standard_Cost AS [Std Cost],
                p.Slu_AW_YesNo_Sell_Below_Cost AS [SellBelowCost],  
        		tc.Tax_Rate as [Tax Rate],                 
                pb.Lup_AP_Product_Bins_ID AS [Bin ID],
                
           		p.Slu_AW_YesNo_Edit_Price AS [Edit Price],
           		p.Slu_AW_YesNo_Edit_Discount AS [Edit Discount],
                p.Slu_AW_YesNo_Cost_Plus_Item AS [IsCostPlusItem],
                p.Lup_AP_Markup_Groups_ID AS [CostPlusGroupID],
                p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem],
                p.Lup_AP_Discount_Groups_ID as [GroupID],
                0 as [Discount %],
                0 as [Discount],
				p.Pack_Mass AS [Pack Mass]
                
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                 (p.Description like @Filter1 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
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Insert_Stock_Transfer_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Insert_Stock_Transfer_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Stock_Transfer_Details
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Insert_Stock_Transfer_Details]
    (
        @CustomerID int,
        @ProductID int,
        @Description varchar(50),
        @ProductCode varchar(20),
        @Quantity decimal(9, 3),
        @BackOrder decimal(9, 3),
        @OriginalPrice money,
        @UnitPrice money,
        @DiscountAmount money,
        @Amount money,
--        @Shipping money,
        @Tax_Rate decimal(9, 3),
        @TaxAmount money,
        @ExtendedAmount money,
        @UnitCost money,
--        @PromoProductID int,
--        @PromoPrice money,
		@Bin_ID Int,
        @DateCaptured datetime,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewOrderID int


    INSERT AP_Stock_Transfer_Details
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Quantity,
            Back_Order,
            Original_Price,
            Unit_Price,
            Discount_Amount,
            Amount,
--            Shipping_Cost,
            Tax_Rate,
            Tax_Amount,
            Extended_Amount,
            Unit_Cost,
--            AP_Promotion_Products_ID,
--            Promo_Price,
			Lup_AP_Product_Bins_ID,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Description,
            @ProductCode,
            @Quantity,
            @BackOrder,
            @OriginalPrice,
            @UnitPrice,
            @DiscountAmount,
            @Amount,
--            @Shipping,
            @Tax_Rate,
            @TaxAmount,
            @ExtendedAmount,
            @UnitCost,
--            @PromoProductID,
--            @PromoPrice,
			@Bin_ID,
            @DateCaptured,
            @UserID,
            @CompanyID
        )


SELECT @NewOrderID = Scope_Identity()


RETURN @NewOrderID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Add_Product_To_Stock_Transfer]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Add_Product_To_Stock_Transfer]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Add_Product_To_Stock_Transfer
--Purpose       :Check if @ProductID EXISTS in Stock Transfer
--				:If EXISTS then UPDATE else ADD new Stock Transfer
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Add_Product_To_Stock_Transfer]
    (
        @CustomerID int,
        @ProductID int,
        @Description varchar(50),
        @ProductCode varchar(20),
        @Quantity decimal(9, 3),
        @BackOrder decimal(9, 3),
        @OriginalPrice money,
        @UnitPrice money,
        @DiscountAmount money,
        @Amount money,
        @Tax_Rate decimal(9, 3),
        @TaxAmount money,
        @ExtendedAmount money,
        @UnitCost money,
        @Bin_ID	int,
        @DateCaptured datetime,
        @UserID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON


    DECLARE @ExistingID int,
            @Last_Qty decimal(9,3),
            @Last_Disc money,
            @New_Qty decimal(9,3),
            @New_Disc money,
            @SubTotal money,
            @Tax money,
            @Total money

    BEGIN

    	SELECT @ExistingID = AP_Stock_Transfer_Details_ID,
               @Last_Qty = Quantity,
               @Last_Disc = Discount_Amount
    	FROM AP_Stock_Transfer_Details
    	WHERE AP_Products_ID = @ProductID AND
    		  AC_Customers_ID = @CustomerID AND
    		  Lup_AP_Product_Bins_ID = @Bin_ID AND
    		  AW_User_Companies_ID = @CompanyID
   	

    	IF @ExistingID is NULL
    		EXEC sp_AP_Insert_Stock_Transfer_Details
                                        @CustomerID,
                                    	@ProductID,
                                    	@Description,
                                    	@ProductCode,
                                    	@Quantity,
                                        @BackOrder,
                                    	@OriginalPrice,
                                    	@UnitPrice,
                                    	@DiscountAmount,
                                    	@Amount,
                                        @Tax_Rate,
                                    	@TaxAmount,
                                    	@ExtendedAmount,
                                    	@UnitCost,
                                    	@Bin_ID,
                                    	@DateCaptured,
                                       	@UserID,
                                       	@CompanyID

    	ELSE


        --> COMBINE the new sales order with existing
            SET @New_Qty = @Last_Qty + @Quantity
            SET @New_Disc = ROUND(@Last_Disc + @DiscountAmount, 2)
            
            SET @SubTotal = ROUND((@UnitPrice * @New_Qty) - @New_Disc, 2)
            SET @Tax = ROUND((@SubTotal * (@Tax_Rate / 100)), 2)
            SET @Total = ROUND(@SubTotal + @Tax, 2)


    		UPDATE AP_Stock_Transfer_Details							
    		SET [Description] = @Description,
                Product_Code = @ProductCode,
                Quantity = @New_Qty,
                Back_Order = @BackOrder,
                Original_Price = @OriginalPrice,
                Unit_Price = @UnitPrice,
                Discount_Amount = @New_Disc,
                Amount = @SubTotal,
                Tax_Rate = @Tax_Rate,
                Tax_Amount = @Tax,
                Extended_Amount = @Total,
                Unit_Cost = @UnitCost,
                Lup_AP_Product_Bins_ID = @Bin_ID,
                Date_Captured = @DateCaptured,
                [User_ID] = @UserID,
                AW_User_Companies_ID = @CompanyID
    		WHERE AP_Stock_Transfer_Details_ID = @ExistingID

    END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Customer_Stock_Transfer_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Customer_Stock_Transfer_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Customer_Stock_Transfer_Details
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2	2016-10-03	RL	:Added Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Customer_Stock_Transfer_Details]
    (
        @CustomerID int,
    	@CompanyID int
    )
AS

SET NOCOUNT ON

   SELECT 
        d.AP_Stock_Transfer_Details_ID AS [ID],
        d.AC_Customers_ID AS [CustomerID],
        d.AP_Products_ID AS [ProductID],
        d.Description AS [Product],
        d.Product_Code AS [Code],
        d.Unit_Price AS [Unit Price],
        d.Quantity AS [Qty],
        d.Back_Order AS [B/O],
        d.Discount_Amount AS [Discount],
        d.Amount AS [Amount],
--        Shipping_Cost AS [Shipping],
        d.Tax_Amount AS [Tax],
        d.Extended_Amount AS [Total],
        d.Tax_Rate AS [Tax Rate],
        d.Original_Price AS [Orig Price],
        d.Unit_Cost AS [UnitCost],
--        AP_Promotion_Products_ID AS [PromoProdID],
--        Promo_Price AS [Promo Price],
		d.Lup_AP_Product_Bins_ID As [BinID],
		b.Description As [Bin],
        d.Date_Captured AS [Captured],
        d.User_ID AS [UserID],
        d.AW_User_Companies_ID AS [CompanyID]
	FROM AP_Stock_Transfer_Details d
	LEFT OUTer JOIN Lup_AP_Product_Bins b
		ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
	WHERE d.AW_User_Companies_ID = @CompanyID AND
          d.AC_Customers_ID = @CustomerID
    ORDER BY d.Date_Captured DESC 


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_RPT_Stock_Transfer_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_RPT_Stock_Transfer_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_RPT_Stock_Transfer_Print
--Purpose       :POS Sales Order printing
--Parameters    :
--Date          :21 AUG 2009
--Authors       :TB
--MODS:         :
--V6.2 RL	2015-11-29	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_RPT_Stock_Transfer_Print]
    (
    	@TransactionID int
    )

AS

SET NOCOUNT ON

    DECLARE @TextMessage varchar(100),
            @TextMessagePrint varchar(100),
            @Message varchar(100),
            @WhichAddress tinyint,
            @WhichName tinyint,
            @PaymentMethod varchar(20),
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0
    SET @Message = ''


    SELECT TOP 1 @TextMessage = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'



    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 @TextMessagePrint = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    IF @TextMessagePrint = '1'
        BEGIN
            SET @Message = @TextMessage
        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 TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''), 20)
	FROM AS_Transactions_Transactions att
        LEFT JOIN AS_Transaction_Payments tp
            ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID
        LEFT JOIN Sys_AW_Payment_Methods pm
            ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID
	WHERE att.Source_AS_Transactions_ID = @TransactionID
    ORDER BY att.Source_AS_Transactions_ID


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [CustomerName],
        ISNULL(c.Firstnames, '') AS [TradeName],
        ISNULL(c.Contact_Name, '') AS [Contact],

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

		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],
-------------------------------------------------------------------------------
		p.Product_Code AS [ProductCode],
		p.Description AS [ProductDescription],
		td.Quantity AS [DetailQty],
		td.Unit_Price AS [DetailUnitPrice],

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

		td.Discount_Amount AS [DetailDiscount],
       (td.Unit_Price * td.Quantity) + td.Discount_Amount AS [DetailAmount],
		td.Tax_Amount AS [DetailTaxAmount],
		td.Extended_Amount AS [DetailExtendedAmount],
        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.Comment AS [Comment],

        ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Cell_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Home_Tel_No)), '') AS [TelNos],
        ISNULL('Fax No ' + RTRIM(LTRIM(c.Fax_No)), '') AS [FaxNo],

        ISNULL(RTRIM(LTRIM(c.Tax_Number)), '') AS [VATNo],

        CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> ''
             THEN 'Jobcard No: ' + RTRIM(LTRIM(ts.Transaction_Numbers))
             ELSE ''
             END AS [JobSource],

        t.AW_User_Companies_ID AS [CompanyID],
        ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass],
        ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Volume, 0), 2) AS [PackVolume],
        @PaymentMethod AS [PayMethod],

        CASE WHEN td.AS_Job_References_ID = 0 
             THEN NULL
             ELSE td.AS_Job_References_ID
             END AS [JobRefNo],

        @Message AS [TextMessage],
        @WhichAddress AS [AddressType],
        td.Serial_No AS [SerialNo],
        td.Make AS [Make],
        td.Customer AS [Customer],
        @WhichName AS [NameType],
        b.description As [Bin]

	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_Details td
            ON t.AS_Transactions_ID = td.AS_Transactions_ID
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AS_Transaction_Sources ts
            ON t.AS_Transactions_ID = ts.AS_Transactions_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
        LEFT JOIN Lup_AP_Product_Bins b
			On b.Lup_AP_Product_Bins_ID = td.Lup_AP_Product_Bins_ID
	WHERE t.AS_Transactions_ID = @TransactionID
    ORDER BY AS_Transaction_Details_ID



SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Shape_Stock_Transfer_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Shape_Stock_Transfer_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Shape_Stock_Transfer_Detail
--Purpose       :Selects Customer Stock Transfer Detail Shaped
--Date          :21 AUG 2009
--Authors       :TB
--Mods          :
--V6.2 RL	2015-11-29	:Added Product Bins
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Shape_Stock_Transfer_Detail] 
    (
        @TransactionID int
    )

AS

SET NOCOUNT ON


    SELECT d.AS_Transaction_Details_ID AS [ID],
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
           d.Unit_Price AS [Unit Price],
           d.Quantity AS [Qty],
           d.Back_Order AS [B/O],
           d.Discount_Amount AS [Discount],
           CONVERT(money, (d.Extended_Amount - d.Tax_Amount)) AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Extended_Amount AS [Total],
           d.Original_Price AS [Orig Price],
           CASE WHEN (d.Extended_Amount - d.Tax_Amount) <> 0
                THEN CONVERT(decimal(9, 3), ROUND((d.Tax_Amount / (d.Extended_Amount - d.Tax_Amount)) * 100, 2))
                ELSE 0.00
           END AS [Tax Rate],
           d.Unit_Cost AS [Unit Cost],
           b.Description As [Bin]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN Lup_AP_Product_Bins b
			On b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID
    ORDER BY [ID]
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Stock_Transfer_Log_Insert_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Stock_Transfer_Log_Insert_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Transfer_Log_Insert_Update
--Purpose       :Insert/Update Stock Transfer Log
--Date          :27 AUG 2009
--Authors       :TB
--MODS          :
--V6.2 RL	2015-11-29	:Added Product Bins
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Stock_Transfer_Log_Insert_Update]
	(
        @ASTranID int = NULL,
        @CustomerID int = NULL, 
        @ProductID int = NULL, 
        @GLTranID int = NULL, 
        @GLTranRef int = NULL, 
        @GLSourceRef varchar(20) = NULL, 
        @Qty decimal(12, 3) = NULL, 
        @OrigPrice money = NULL, 
        @UnitCost money = NULL, 
        @UnitPrice money = NULL, 
        @DiscAmount money = NULL, 
        @Amount money = NULL, 
        @TaxAmount money = NULL, 
        @TotalAmount money = NULL, 
        @GRVID int = NULL, 
        @DateReceived datetime = NULL, 
        @BinID	int,
        @SITUserID int = NULL, 
        @TRFUserID int = NULL, 
        @CompanyID int = NULL, 
        @TrfLogID int = NULL OUTPUT
	)

AS

SET NOCOUNT ON

    DECLARE @TranDate datetime,
            @DateCaptured datetime


    SET @TranDate = getdate()
    SET @DateCaptured = @TranDate


    IF @ASTranID > 0
        BEGIN
            SELECT @TranDate = Transaction_Date,
                   @DateCaptured = Date_Captured
            FROM AS_Transactions
            WHERE AS_Transactions_ID = @ASTranID
        END


	IF @TrfLogID IS NULL OR @TrfLogID = 0
		BEGIN
			INSERT AP_Stock_Transfer_Log
                (
                    AS_Transactions_ID,
                    AC_Customers_ID,
                    AP_Products_ID,
                    AB_GL_Transactions_ID,
                    AB_Transaction_Ref,
                    AB_Source_Ref,
                    Transaction_Date,
                    Quantity,
                    Original_Price,
                    Unit_Cost,
                    Unit_Price,
                    Discount_Amount,
                    Amount,
                    Tax_Amount,
                    Extended_Amount,
                    AO_GRV_ID,
                    Date_Received,
                    SIT_User_ID,
                    Date_Captured,
                    TRF_User_ID,
                    AW_User_Companies_ID,
                    Lup_AP_Product_Bins_ID
                )
			VALUES
				(
                    @ASTranID,
                    @CustomerID,
                    @ProductID,
                    @GLTranID,
                    @GLTranRef,
                    @GLSourceRef,
                    @TranDate,
                    @Qty,
                    @OrigPrice,
                    @UnitCost,
                    @UnitPrice,
                    @DiscAmount,
                    @Amount,
                    @TaxAmount,
                    @TotalAmount,
                    @GRVID,
                    @DateReceived,
                    @SITUserID,
                    @DateCaptured,
                    @TRFUserID,
                    @CompanyID,
                    @BinID
				)
			SELECT @TrfLogID = Scope_Identity()
		END		
	ELSE
        BEGIN
    		UPDATE AP_Stock_Transfer_Log
            SET AS_Transactions_ID = @ASTranID,
                AC_Customers_ID = @CustomerID,
                AP_Products_ID =  @ProductID,
                AB_GL_Transactions_ID = @GLTranID,
                AB_Transaction_Ref = @GLTranRef,
                AB_Source_Ref = @GLSourceRef,
                Transaction_Date = @TranDate,
                Quantity = @Qty,
                Original_Price = @OrigPrice,
                Unit_Cost = @UnitCost,
                Unit_Price = @UnitPrice,
                Discount_Amount = @DiscAmount,
                Amount = @Amount,
                Tax_Amount = @TaxAmount,
                Extended_Amount = @TotalAmount,
                AO_GRV_ID = @GRVID,
                Date_Received = @DateReceived,
                SIT_User_ID = @SITUserID,
                Date_Captured = @DateCaptured,
                TRF_User_ID = @TRFUserID,
                AW_User_Companies_ID = @CompanyID,
                Lup_AP_Product_Bins_ID = @BinID
            WHERE AP_Stock_Transfer_Log_ID = @TrfLogID
        END


	RETURN @TrfLogID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Stock_Transfer_Back_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Stock_Transfer_Back_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Stock_Transfer_Back_Orders
--Purpose       :
--Date          :21 AUG 2009
--Authors       :TB
--MODS          :
--V6.2 RL	2015-11-29	:Added Product Bins
---------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Select_Stock_Transfer_Back_Orders]
    (
    	@CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @OrderType tinyint = 0,
        @SortOption tinyint = 0
    )

AS

SET NOCOUNT ON


    IF @OrderType = 0        --Back Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Product], s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Back_Order AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Back_Order <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], s.Date_Captured
                END
        END

    ELSE                    --Stock Transfers
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
						b.Description As [Bin],                       
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Product], s.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
                   SELECT 
                        s.AP_Stock_Transfer_Details_ID AS [ID],
                        s.AC_Customers_ID AS [CustomerID],
                        s.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        s.[Description] AS [Product],
                        s.Product_Code AS [Code],
                        s.Unit_Price AS [Unit Price],
                        s.Quantity AS [Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty on Hand],
                		p.On_Hand AS [On Hand], 
                        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],
                        b.Description As [Bin],
                        s.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        s.[User_ID] AS [UserID],
                        s.AW_User_Companies_ID AS [CompanyID]
                	FROM AP_Stock_Transfer_Details s
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = s.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = s.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = s.[User_ID]
                        LEFT JOIN Lup_AP_Product_Bins b
							On b.Lup_AP_Product_Bins_ID = s.Lup_AP_Product_Bins_ID
                	WHERE s.AW_User_Companies_ID = @CompanyID AND
                          s.Quantity <> 0 AND
                         (DATEDIFF(d, s.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, s.Date_Captured, @EndDate) >= 0) AND
                          s.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], s.Date_Captured
                END
        END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Stock_Transfer_Log]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Stock_Transfer_Log]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Stock_Transfer_Log
--Purpose       :Selects Stock Transfer Log
--Date          :27 AUG 2009
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Stock_Transfer_Log]
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint = 0
	)

AS

SET NOCOUNT ON


        IF @SortOrder = 0
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Tranfer Date]
            END
        ELSE
        IF @SortOrder = 1
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Product], [Tranfer Date]
            END
        ELSE
        IF @SortOrder = 2
            BEGIN
                SELECT
                    l.AS_Transactions_ID AS [ID],
                    l.AC_Customers_ID AS [CustomerID],
                    l.AP_Products_ID AS [ProductID],
                    l.AB_GL_Transactions_ID AS [SITGLID],
                    l.AB_Transaction_Ref AS [GLRefID],
                    l.AB_Source_Ref AS [GLSourceRef],
                    l.Transaction_Date AS [Tranfer Date],
                    ISNULL(c.Surname, '') AS [Customer],
                    ISNULL(h.Transaction_Number, '') AS [Trf No],
                    ISNULL(gl.Description, '') AS [GL Account],
                    m.[Description] AS [Month],
                    y.[Description] AS [Year],
                    CONVERT(datetime, CONVERT(CHAR(10), l.Date_Received, 121)) AS [Received], 
                    l.AO_GRV_ID AS [GRV No],
                    tu.UserName AS [SIT User],
                    ISNULL(p.Description, '') AS [Product],
                    ISNULL(p.Product_Code, '') AS [Code],
                    l.Quantity AS [Qty],
                    b.Description As [Bin],
                    l.Original_Price AS [Orig Price],
                    l.Unit_Cost AS [Cost],
                    l.Unit_Price AS [Unit Price],
                    l.Discount_Amount AS [Discount],
                    l.Amount AS [Amount],
                    l.Tax_Amount AS [Tax],
                    l.Extended_Amount AS [Total],
                    h.Comment AS [Notes],
                    u.UserName AS [User]
                FROM AP_Stock_Transfer_Log l
                    INNER JOIN AS_Transactions h
                        ON l.AS_Transactions_ID = h.AS_Transactions_ID
                    INNER JOIN AC_Customers c
                        ON l.AC_Customers_ID = c.AC_Customers_ID
                    INNER JOIN AP_Products p
                        ON l.AP_Products_ID = p.AP_Products_ID
                    INNER JOIN AB_GL_Transactions gt
                        ON l.AB_GL_Transactions_ID = gt.AB_GL_Transactions_ID
                    INNER JOIN AB_Accounts gl
                        ON gt.AB_Accounts_ID = gl.AB_Accounts_ID
                    LEFT JOIN Slu_AW_Months m
                        ON gt.Slu_AW_Months_ID = m.Slu_AW_Months_ID
                    LEFT JOIN Slu_AW_Years y
                        ON gt.Slu_AW_Years_ID = y.Slu_AW_Years_ID
                    LEFT JOIN AW_Users u
                        ON l.TRF_User_ID = u.AW_Users_ID
                    LEFT JOIN AW_Users tu
                        ON l.SIT_User_ID = tu.AW_Users_ID
					LEFT JOIN Lup_AP_Product_Bins b
						On b.Lup_AP_Product_Bins_ID = l.Lup_AP_Product_Bins_ID
                WHERE l.AW_User_Companies_ID = @CompanyID AND
                     (DATEDIFF(d, l.Transaction_Date, @StartDate) <= 0 AND
                      DATEDIFF(d, l.Transaction_Date, @EndDate) >= 0)
                ORDER BY [Customer], [Tranfer Date]
            END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_Remote_Sites_IP]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_Remote_Sites_IP]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AW_Select_Remote_Sites_IP
--Purpose       :Retrieves Remote Sites Data Server and Instance Names
--Date          :2016-10-04
--Authors       :RL
--MODS          :
----------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

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

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

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

SET NOCOUNT ON

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

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

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

	SELECT @BackOrder = ISNULL(@BackOrder,0)

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

--Insert Into Temp_Debug Values('27 - @TransactionTypeID',Convert(Varchar(100),@TransactionTypeID))  

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

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

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


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


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

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

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

	SELECT @DocumentDetailsID = 0

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

	--If @DocumentDetailsID = 0, Insert will be done later

	IF @TransactionTypeID In (1, 2, 3, 13, 16, 33)
	BEGIN

		IF @BackOrder <> 0 
		BEGIN

			IF @OldTransactionTypeID >= -99
			BEGIN

				EXEC sp_AS_POS_Add_BO_To_SO
											@DocumentID,
											@ProductID,
											@BackOrder,
											@Qty,
											@Cost,
											@Price,
											@OriginalPrice,
											@Discount,
											@Tax,
											@TotalAmount,
											@Commission,
											@PromotionProductID,
											@PromotionPrice,
											@JobRefID,
											@SerialNo,
											@Make,
											@Customer,
											@TDHeader,
											@TDDetail,
											@ProductBinsID,
											@TransactionTypeID,
											@OldTransactionTypeID,
											@UserID,
											@CompanyID
			END

			IF @TransactionTypeID <> 16
				SET @BackOrder = 0

		END
	END

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

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

RETURN @DocumentDetailsID
GO
--Insert Consignment Stock Transaction Types
IF NOT EXISTS
(
	SELECT 1
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Inventory'
) 
BEGIN

	INSERT AB_Accounts
	(		
		[Description], 
		Account_Number, 
		Sys_AB_Account_Categories_ID, 
		Sys_AW_Tax_Codes_ID, 
		Lup_AB_Cost_Centers_ID, 
		AB_Account_Balance, 
		Opening_Balance, 
		Opening_Date, 
		Opening_Month, 
		Opening_Year, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		AW_YesNo_Controllable_ID, 
		Lup_AB_Account_Groups_ID, 
		Lup_AB_Account_Divisions_ID
	)
	VALUES
	(
		'Consignment Inventory',		--[Description]
		'',								--Account_Number
		49,								--Sys_AB_Account_Categories_ID
		1,								--Sys_AW_Tax_Codes_ID
		1,								--Lup_AB_Cost_Centers_ID, 
		0.00,							--AB_Account_Balance, 
		0.00,							--Opening_Balance, 
		'2015-03-01',					--Opening_Date, 
		3,								--Opening_Month, 
		16,								--Opening_Year, 
		GETDATE(),						--Date_Captured, 
		1,								--User_ID, 
		1,								--AW_User_Companies_ID, 
		1,								--Slu_AW_Active_ID, 
		1,								--AW_YesNo_Controllable_ID, 
		1,								--Lup_AB_Account_Groups_ID, 
		1								--Lup_AB_Account_Divisions_ID
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Trade Creditors'
) 
BEGIN

	INSERT AB_Accounts
	(		
		[Description], 
		Account_Number, 
		Sys_AB_Account_Categories_ID, 
		Sys_AW_Tax_Codes_ID, 
		Lup_AB_Cost_Centers_ID, 
		AB_Account_Balance, 
		Opening_Balance, 
		Opening_Date, 
		Opening_Month, 
		Opening_Year, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		AW_YesNo_Controllable_ID, 
		Lup_AB_Account_Groups_ID, 
		Lup_AB_Account_Divisions_ID
	)
	VALUES
	(
		'Consignment Trade Creditors',	--[Description]
		'',								--Account_Number
		49,								--Sys_AB_Account_Categories_ID
		1,								--Sys_AW_Tax_Codes_ID
		1,								--Lup_AB_Cost_Centers_ID, 
		0.00,							--AB_Account_Balance, 
		0.00,							--Opening_Balance, 
		'2015-03-01',					--Opening_Date, 
		3,								--Opening_Month, 
		16,								--Opening_Year, 
		GETDATE(),						--Date_Captured, 
		1,								--User_ID, 
		1,								--AW_User_Companies_ID, 
		1,								--Slu_AW_Active_ID, 
		1,								--AW_YesNo_Controllable_ID, 
		1,								--Lup_AB_Account_Groups_ID, 
		1								--Lup_AB_Account_Divisions_ID
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Trade Debtors'
) 
BEGIN

	INSERT AB_Accounts
	(		
		[Description], 
		Account_Number, 
		Sys_AB_Account_Categories_ID, 
		Sys_AW_Tax_Codes_ID, 
		Lup_AB_Cost_Centers_ID, 
		AB_Account_Balance, 
		Opening_Balance, 
		Opening_Date, 
		Opening_Month, 
		Opening_Year, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		AW_YesNo_Controllable_ID, 
		Lup_AB_Account_Groups_ID, 
		Lup_AB_Account_Divisions_ID
	)
	VALUES
	(
		'Consignment Trade Debtors',	--[Description]
		'',								--Account_Number
		49,								--Sys_AB_Account_Categories_ID
		1,								--Sys_AW_Tax_Codes_ID
		1,								--Lup_AB_Cost_Centers_ID, 
		0.00,							--AB_Account_Balance, 
		0.00,							--Opening_Balance, 
		'2015-03-01',					--Opening_Date, 
		3,								--Opening_Month, 
		16,								--Opening_Year, 
		GETDATE(),						--Date_Captured, 
		1,								--User_ID, 
		1,								--AW_User_Companies_ID, 
		1,								--Slu_AW_Active_ID, 
		1,								--AW_YesNo_Controllable_ID, 
		1,								--Lup_AB_Account_Groups_ID, 
		1								--Lup_AB_Account_Divisions_ID
	)
END
GO


IF NOT EXISTS
(
	SELECT 1
	FROM AB_Accounts
	WHERE [Description] = 'Consignment TAX'
) 
BEGIN

	INSERT AB_Accounts
	(		
		[Description], 
		Account_Number, 
		Sys_AB_Account_Categories_ID, 
		Sys_AW_Tax_Codes_ID, 
		Lup_AB_Cost_Centers_ID, 
		AB_Account_Balance, 
		Opening_Balance, 
		Opening_Date, 
		Opening_Month, 
		Opening_Year, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		AW_YesNo_Controllable_ID, 
		Lup_AB_Account_Groups_ID, 
		Lup_AB_Account_Divisions_ID
	)
	VALUES
	(
		'Consignment TAX',			--[Description]
		'',								--Account_Number
		49,								--Sys_AB_Account_Categories_ID
		1,								--Sys_AW_Tax_Codes_ID
		1,								--Lup_AB_Cost_Centers_ID, 
		0.00,							--AB_Account_Balance, 
		0.00,							--Opening_Balance, 
		'2015-03-01',					--Opening_Date, 
		3,								--Opening_Month, 
		16,								--Opening_Year, 
		GETDATE(),						--Date_Captured, 
		1,								--User_ID, 
		1,								--AW_User_Companies_ID, 
		1,								--Slu_AW_Active_ID, 
		1,								--AW_YesNo_Controllable_ID, 
		1,								--Lup_AB_Account_Groups_ID, 
		1								--Lup_AB_Account_Divisions_ID
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header_Consignment
--Purpose       :Selects POS Transaction Header Shaped for Customer Consignment Stock
--Date          :2015/05/18
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment]
	(
        @CustomerID int,
        @SearchString varchar(50),
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @CompanyID int
	)

AS

SET NOCOUNT ON

-------------------------------------------------------------------------------
 IF @CustomerID <> 0
 BEGIN --@CustomerID <> 0
	
	IF @TransactionTypeID <> 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_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) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_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) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	IF @TransactionTypeID = 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				 DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep]
			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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
			     DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		
			
END --@CustomerID <> 0


IF @CustomerID = 0
 BEGIN --@CustomerID <> 0
	
	IF @TransactionTypeID <> 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				t.Sys_AW_Transaction_Types_ID = @TransactionTypeID 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		

--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	IF @TransactionTypeID = 0
	BEGIN --Specific Transaction Type
                
--------------------------------------------->>>>>>>
		IF @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
	
			SET @SearchString = '%' +  @SearchString + '%'
            
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
				td.Quantity   
							- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
							- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep],
				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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				 DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
				(
					(t.Transaction_Number like @SearchString) OR
					(p.Product_Code like @SearchString) OR
					(p.Description like @SearchString) OR
					(ISNULL(t.Customer_Reference,'') like @SearchString)
				) 						 
			ORDER BY t.Transaction_Date DESC
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
				t.AS_Transactions_ID AS [ID],
				td.AS_Transaction_Details_ID AS [DetailID],
				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],
				p.Product_Code AS [Product Code],
				p.Description AS [Product Description],
				td.Quantity AS  [Quantity],
				dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced],
				dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
				td.Unit_Price As [Unit Price],
				td.Discount_Amount AS [Discount],
				td.Tax_Amount AS [VAT],
				td.Extended_Amount AS [Total Amount],
				td.Unit_Cost AS [Total Cost],
				ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                act.[Description] AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
				ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
				ISNULL(r.[Description],'') AS [Sales Rep]
			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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID
				LEFT OUTER JOIN Lup_AS_Reps r
					ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID					
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				(t.Sys_AW_Transaction_Types_ID = 33 OR --Consignment Stock Note
				 t.Sys_AW_Transaction_Types_ID = 34 OR --Consignment Stock Sold
				 t.Sys_AW_Transaction_Types_ID = 35) AND --Consignment Stock Returned
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
			     DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
	END --Specific Transaction Type		
			
END --@CustomerID = 0
Go
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Customer_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Customer_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Select_Customer_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/03/15
--Authors       :TB
--MODS          :24/07/02 - Added Sys_AW_Transactions_Types_ID's 21 and 22 to
--              :           @Choice=17 (Customer Catalog cboCustTrans)
--              :04/08/03 - Added Choice 18 & 19, Transaction Types - Quotes, 
--              :           Jobcards, Proformas and Users for Deactivate Transactions
--              :06/08/03 - Added Choice 20 Active for Deactivate Transactions
--              :09/08/03 - Added Choice 21 ALL Transaction Types - Sales Chronolgy
--              :20/12/03 - Added Choice 22 Use Assets in Customer Catalog
--              :04/01/04 - Added Choice 23 to 48 for Credit Manager
--              :05/07/04 - Added Choice 49 for Lup_AC_Customer_Groups
--              :05/01/05 - Added Choice 50 for Customers Payments History
--2004.2.7      :10/03/06 - Added Choice = 51 for Customer E-Mail addresses
--2004.3.7      :25/07/07 - Added Choice = 52 for Customer Cost+Plus Category
--2004.3.8      :02/12/07 - Added ORDER BY for Reps, Countries, Customer Type,
--              :           Sales Areas, and Customer Groups
--2004.3.9      :05/07/08 - Added new Select Sales Order TranType = 16 where required
--2004.4.3      :17/03/09 - Added Option = 53 for Statement Messages - Active only
--2004.4.7      :22/08/09 - Added new Select Stock Transfer TranType = 23 where required
--2004.5.0      :16/11/10 - Change alias in Choice 51 from [EMail] to [E-Mail] for Periodic Billing
--              :21/01/11 - Added Option = 54 for Periodic Billing
--V6.2	RL	2015-05-18	:Added Option 56 - Customer Consignment Stock Transaction Types
--V6.2	RL	2015-06-10	:Added Customer Consignment Transactions to options 17 and 21
-------------------------------------------------------------------------------


CREATE PROCEDURE [dbo].[sp_AC_Select_Customer_Lups]
    (
       	@Choice int,
    	@CompanyID int
    )
AS

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ELSE
    IF @Choice = 51 --Customer E-Mail addresses
        SELECT Orders_URL as [E-Mail]
        FROM AC_Customers
        WHERE AC_Customers_ID = @CompanyID

        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

    ELSE
    IF @Choice = 56 --Customer COnsignment Stock Transactions Types
        SELECT Sys_AW_Transaction_Types_ID as [ID],
              [Description] AS [Transaction Type]
        FROM Sys_AW_Transaction_Types
        WHERE Sys_AW_Transaction_Types_ID = 33 or
              Sys_AW_Transaction_Types_ID = 34 or
              Sys_AW_Transaction_Types_ID = 35
    ELSE
    IF @Choice = 57 --Customer COnsignment Stock Transactions Types
        SELECT Lup_AP_Product_Bins_ID as [ID],
              [Description] AS [ProductBin]
        FROM Lup_AP_Product_Bins
        ORDER BY [Description]

END  
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Consignment_Customers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Consignment_Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Select_Consignment_Customers
--Purpose       :Select all Customers that had or has had consignment stock
--Functionality :
--Parameters    :
--Date          :2015-05-20
--Authors       :RL
------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AC_Select_Consignment_Customers]
    (
    	@Company_ID int
    )

AS

SET NOCOUNT ON
	
	SELECT Distinct c.AC_Customers_ID AS [ID],
		   ISNULL(Surname,'') + ISNULL(', ' + Firstnames,'') AS [Customer],
           ISNULL(Customer_Number, '') AS [Cust No],
           Sys_AC_Account_Types_ID AS [Account_Type]
	FROM AC_Customers c
		INNER JOIN AS_Transactions t
			ON c.AC_Customers_ID = t.AC_Customers_ID
		INNER JOIN AS_Transaction_Details d
			ON t.AS_Transactions_ID = d.AS_Transactions_ID
	WHERE c.AW_User_Companies_ID = @Company_ID
	AND t.Sys_AW_Transaction_Types_ID = 33
	AND d.Quantity 	- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
					- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0
	ORDER BY [Customer] ASC

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

-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Header_Insert_Cons
--Purpose       :INSERTS CUSTOMER TRANSACTIONS for consignment stock
--Functionality :Financial AS_Transactions types only: 34, 35
--              :NB NB - SIGN REVERSAL
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transaction_Header_Insert_Cons]
    (
        @TranDate		datetime,
    	@CustomerID		int,
    	@TranTypeID		tinyint,
        @RefNo			varchar(19),
        @TotalCost		money,
        @Amount			money,
        @Discount		money,
        @Tax			money,
        @Total			money,
    	@GLAccountID	int,
    	@Comment		varchar(20),
    	@Order_No		varchar(15),
    	@Notes			varchar(500),
        @DatePosted		datetime,
        @Reps_ID		int,
    	@UserID			int,
    	@CompanyID		int
    )
AS

	DECLARE @DocumentID int,
            @CommentID int

    IF @TranTypeID = 34 OR @TranTypeID = 35 OR @TranTypeID = 3
        BEGIN
            IF RTRIM(LTRIM(@Notes)) <> ''
                BEGIN
                    EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
                END
        END

    SET @GLAccountID = NULL

	IF @TranTypeID <> 3
	BEGIN
		SET @TotalCost = @TotalCost * -1
		SET @Amount = @Amount * -1
		SET @Tax = @Tax * -1
		SET @Total = @Total * -1
	END

	INSERT AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Discount_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            Lup_AS_Reps_ID,
            [User_ID],
            AW_User_Companies_ID
		)			
	VALUES
		(
            @CustomerID,
            @GLAccountID,
            @RefNo,
            @TotalCost,
            @Amount,
            @Tax,
            @Discount,
            @Total,
            @TranDate,
            @Order_No,
            @Comment,
            @CommentID,
            @UserID,
            @TranTypeID,
            @DatePosted,
            @Reps_ID,
            @UserID,
            @CompanyID
		)

    SELECT @DocumentID = Scope_Identity()

	IF @TranTypeID = 3
	BEGIN
		--> Update the Customer Account Balance
		UPDATE AC_Customers
		SET Account_Balance = Account_Balance + @Total
		WHERE AC_Customers_ID = @CustomerID
	END

RETURN @DocumentID
GO
IF NOT EXISTS
(
	SELECT * from syscolumns 
	where id = Object_ID('AB_Control_Accounts') 
	and colstat & 1 = 1
)
BEGIN
	Declare @AB_Control_Accounts_ID smallint
		
	IF NOT EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE [Description] = 'Consignment Inventory'
	) 
	BEGIN

		SELECT @AB_Control_Accounts_ID = MAX(AB_Control_Accounts_ID)
		FROM AB_Control_Accounts

		INSERT AB_Control_Accounts
		(	
			AB_Control_Accounts_ID,
			Control_Number, 
			[Description], 
			User_Description, 
			AB_Accounts_ID, 
			Date_Captured, 
			User_ID, 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID, 
			Control_Type	
		)
		SELECT
			@AB_Control_Accounts_ID + 1,
			'701',
			'Consignment Inventory',
			'Consignment Inventory',
			AB_Accounts_ID,
			GETDATE(),
			1,
			1,
			1,
			0
		FROM AB_Accounts
		WHERE [Description] = 'Consignment Inventory'					
	END
	

	IF NOT EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE [Description] = 'Consignment Trade Creditors'
	) 
	BEGIN

		SELECT @AB_Control_Accounts_ID = MAX(AB_Control_Accounts_ID)
		FROM AB_Control_Accounts

		INSERT AB_Control_Accounts
		(	
			AB_Control_Accounts_ID,
			Control_Number, 
			[Description], 
			User_Description, 
			AB_Accounts_ID, 
			Date_Captured, 
			User_ID, 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID, 
			Control_Type	
		)
		SELECT
			@AB_Control_Accounts_ID + 1,
			'702',
			'Consignment Trade Creditors',
			'Consignment Trade Creditors',
			AB_Accounts_ID,
			GETDATE(),
			1,
			1,
			1,
			0
		FROM AB_Accounts
		WHERE [Description] = 'Consignment Trade Creditors'					
	END
	

	IF NOT EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE [Description] = 'Consignment Trade Debtors'
	) 
	BEGIN

		SELECT @AB_Control_Accounts_ID = MAX(AB_Control_Accounts_ID)
		FROM AB_Control_Accounts

		INSERT AB_Control_Accounts
		(	
			AB_Control_Accounts_ID,
			Control_Number, 
			[Description], 
			User_Description, 
			AB_Accounts_ID, 
			Date_Captured, 
			User_ID, 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID, 
			Control_Type	
		)
		SELECT
			@AB_Control_Accounts_ID + 1,
			'703',
			'Consignment Trade Debtors',
			'Consignment Trade Debtors',
			AB_Accounts_ID,
			GETDATE(),
			1,
			1,
			1,
			0
		FROM AB_Accounts
		WHERE [Description] = 'Consignment Trade Debtors'					
	END
	
	IF NOT EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE [Description] = 'Consignment V.A.T'
	) 
	BEGIN

		SELECT @AB_Control_Accounts_ID = MAX(AB_Control_Accounts_ID)
		FROM AB_Control_Accounts

		INSERT AB_Control_Accounts
		(	
			AB_Control_Accounts_ID,
			Control_Number, 
			[Description], 
			User_Description, 
			AB_Accounts_ID, 
			Date_Captured, 
			User_ID, 
			AW_User_Companies_ID, 
			Slu_AW_Active_ID, 
			Control_Type	
		)
		SELECT
			@AB_Control_Accounts_ID + 1,
			'704',
			'Consignment V.A.T',
			'Consignment V.A.T',
			AB_Accounts_ID,
			GETDATE(),
			1,
			1,
			1,
			0
		FROM AB_Accounts
		WHERE [Description] = 'Consignment V.A.T'					
	END


END
GO
--Insert Consignment Control Accounts
IF NOT EXISTS
(
	SELECT 1
	FROM AB_Control_Accounts
	WHERE [Description] = 'Consignment Inventory'
) 
BEGIN

	INSERT AB_Control_Accounts
	(	
		Control_Number, 
		[Description], 
		User_Description, 
		AB_Accounts_ID, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		Control_Type	
	)
	SELECT
		'701',
		'Consignment Inventory',
		'Consignment Inventory',
		AB_Accounts_ID,
		GETDATE(),
		1,
		1,
		1,
		0
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Inventory'					
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM AB_Control_Accounts
	WHERE [Description] = 'Consignment Trade Creditors'
) 
BEGIN

	INSERT AB_Control_Accounts
	(	
		Control_Number, 
		[Description], 
		User_Description, 
		AB_Accounts_ID, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		Control_Type	
	)
	SELECT
		'702',
		'Consignment Trade Creditors',
		'Consignment Trade Creditors',
		AB_Accounts_ID,
		GETDATE(),
		1,
		1,
		1,
		0
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Trade Creditors'					
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM AB_Control_Accounts
	WHERE [Description] = 'Consignment Trade Debtors'
) 
BEGIN

	INSERT AB_Control_Accounts
	(	
		Control_Number, 
		[Description], 
		User_Description, 
		AB_Accounts_ID, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		Control_Type	
	)
	SELECT
		'703',
		'Consignment Trade Debtors',
		'Consignment Trade Debtors',
		AB_Accounts_ID,
		GETDATE(),
		1,
		1,
		1,
		0
	FROM AB_Accounts
	WHERE [Description] = 'Consignment Trade Debtors'					
END	
GO
IF NOT EXISTS
(
	SELECT 1
	FROM AB_Control_Accounts
	WHERE [Description] = 'Consignment V.A.T'
) 
BEGIN

	INSERT AB_Control_Accounts
	(	
		Control_Number, 
		[Description], 
		User_Description, 
		AB_Accounts_ID, 
		Date_Captured, 
		User_ID, 
		AW_User_Companies_ID, 
		Slu_AW_Active_ID, 
		Control_Type	
	)
	SELECT
		'704',
		'Consignment V.A.T',
		'Consignment V.A.T',
		AB_Accounts_ID,
		GETDATE(),
		1,
		1,
		1,
		0
	FROM AB_Accounts
	WHERE [Description] = 'Consignment V.A.T'					
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Detail_Insert_Cons]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Detail_Insert_Cons]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Detail_Insert_Cons
--Purpose       :INSERTS CUSTOMER TRANSACTION DETAILS for consignment stock
--              :    also UPDATES AP_Products: On_Hand, Last_Sale_Date
--              :         UPDATES AS_Transactions: Total_Cost
--Functionality :AS_Transactions types with Detail only: 34, 35
--              :NB NB - Qty and Amounts SIGN REVERSAL DONE IN UI
--Date          :2015-05-21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Transaction_Detail_Insert_Cons]
    (
		@DocumentID		int,
		@TranTypeID		int,
		@Qty			decimal(9,3),
		@OriginalPrice	money,
		@UnitPrice		money,
		@Discount		money,
		@Tax			money,
        @Total			money,
        @DatePosted		datetime,
        @ConsignmentID	int,
		@UserID			int,
		@CompanyID		int
    )
AS

SET NOCOUNT ON

	DECLARE @DocumentDetailsID		int,
            @Cost					money,
            @TotalCost				money,    		
    		@ProductID				int,
			@IsConsignmentStock		int,
			@Oppisite_Qty			decimal(9,3),
			@ProductBinID			int,
			@ProductsQty			decimal(9,3),		

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

    SET @DocumentDetailsID = 0

	SELECT @Cost = Unit_Cost,
		   @ProductID = AP_Products_ID,
		   @ProductBinID = Lup_AP_Product_Bins_ID
	FROM AS_Transaction_Details
	WHERE AS_Transaction_Details_ID = @ConsignmentID
 
	IF ( (@TranTypeID = 34))	--Consignment Sold
	BEGIN
		--SET @IsConsignmentStock = 0
		--EXEC sp_AS_Transaction_Detail_Consignment_Check @ProductID, @Qty, @UserID, @CompanyID, @IsConsignmentStock OUTPUT	
		
		--IF @IsConsignmentStock = 1
		--BEGIN
		
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @ProductID

--Insert Into Temp_Debug Values('40 - @ConsignmentID',Convert(Varchar(100),@ConsignmentID))   	
--Insert Into Temp_Debug Values('40 - @Qty',Convert(Varchar(100),@Qty))   	
--Insert Into Temp_Debug Values('40 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
		
			UPDATE AP_Products
			SET On_Hand = On_Hand + @Qty,
			[User_ID] = @UserID
			WHERE AP_Products_ID = @ProductID
			
			--V6.2 Update Bin Qty
			IF @Qty <> 0
			BEGIN
				--SELECT @Oppisite_Qty = @Qty
				
				EXEC sp_AP_Products_Bins_Update_Insert 
					@ProductID,							--@ProductID int,
					@ProductBinID,						--@ProductBinID int,
					@Qty,								--@Qty decimal(9,3)
					'Cons Sale',						--@Source varchar(10),
					0,									--@Batch_No
					@UserID,							--@UserID int,
					@CompanyID							--@CompanyID int			    	
			END	
			
		--END			
				    
		SET @TotalCost = ( ROUND(@Qty * @Cost, 2) * -1)
		SET @Discount = @Discount

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

	END
	ELSE
	BEGIN --Consignment Returned

		UPDATE AP_Products
		SET On_Hand = On_Hand + @Qty,
		[User_ID] = @UserID
		WHERE AP_Products_ID = @ProductID
    
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SELECT @Oppisite_Qty = @Qty
			
			EXEC sp_AP_Products_Bins_Update_Insert 
				@ProductID,							--@ProductID int,
				@ProductBinID,						--@ProductBinID int,
				@Qty,								--@Qty decimal(9,3)
				'ConsReturn',						--@Source varchar(10),
				0,									--@Batch_No
				@UserID,							--@UserID int,
				@CompanyID							--@CompanyID int			    	
		END	
		
		SET @TotalCost = ( ROUND(@Qty * @Cost, 2) * -1)

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

	INSERT AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		)
	VALUES
		(
			@DocumentID,
			@ProductID,
			(@Qty * -1),
			@Cost,
			@UnitPrice,
			@OriginalPrice,
			@Discount,
			(@Tax * -1),
			(@Total * -1),
            '',
            '',
            '',
            '',
            @DatePosted,
			@UserID,
			@CompanyID,
			@ProductBinID
		)

	SELECT @DocumentDetailsID = Scope_Identity()

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

	INSERT INTO AS_Transaction_Details_Consignment
	(		
		AS_Transaction_Details_ID, --Sys_AW_Transaction_Types_ID 33 Consignment Stock Note
		Consignment_ID,
		Sys_AW_Transaction_Types_ID,
		Quantity,
		Date_Captured,
		[User_ID],
		AW_User_Companies_ID	
	)
	VALUES
	(
		@ConsignmentID,
		@DocumentDetailsID,
		@TranTypeID,
		(@Qty),
		@DatePosted,
		@UserID,
		@CompanyID
	)

RETURN @DocumentDetailsID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transaction_Invoice_Cons]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transaction_Invoice_Cons]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transaction_Invoice_Cons
--Purpose       :Create an Invoice for Consignment stock sold
--Functionality :Financial AS_Transactions types only: 3
--              :NB NB - SIGN REVERSAL
--Authors       :RL
--Date          :2015/05/21
--MODS          :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Transaction_Invoice_Cons]
    (
        @SoldConsignmentID int,
        @ConsignmentID int,
        @CustomerID int,
        @Notes varchar(500),
        @Total money,
        @Reps_ID		int,
    	@UserID int,
    	@CompanyID int
    )

AS

	DECLARE @DocumentID					int,
			@DocumentDetailsID			int,
            @CommentID					int,
            @Transaction_Number			varchar(19),
            @AS_Transaction_Details_ID	int, 
            @AP_Products_ID				int, 
            @Quantity					decimal(9,3),
            @Quantity_Cons				decimal(9,3),
            @Detail_Date_Captured		datetime,
   			@IsConsignmentStock			int,
			@CostingMethod				int,
			@Cost						money,
			@Cost_Original				money,
			@Cost_Diff					money,
			@Oppisite_Qty				decimal(9,3),
			@ProductBinID				int,
			@ProductsQty				decimal(9,3),

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

	EXEC sp_AW_Get_Next_Transaction_Number 3, 1, @Transaction_Number Output

	IF RTRIM(LTRIM(@Notes)) <> ''
	BEGIN
		EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Notes
	END
	
	INSERT INTO AS_Transactions
		(
            AC_Customers_ID,
            AB_Accounts_ID,
            Transaction_Number,
            Total_Cost,
            Amount,
            Total_Tax_Amount,
            Total_Discount_Amount,
            Total_Amount,
            Transaction_Date,
            Customer_Reference,
            Comment,
            AW_Comments_ID,
            Lup_AS_Cashiers_ID,
            Sys_AW_Transaction_Types_ID,
            Date_Captured,
            Lup_AS_Reps_ID,
            [User_ID],
            AW_User_Companies_ID
		)
	SELECT  AC_Customers_ID,
            AB_Accounts_ID,
            @Transaction_Number,
            (Total_Cost*-1),
            (Amount*-1),
            (Total_Tax_Amount*-1),
            (Total_Discount_Amount*-1),
            (Total_Amount*-1),
            Transaction_Date,
            Customer_Reference,
            Comment,
            @CommentID,
            Lup_AS_Cashiers_ID,
            3,
            Date_Captured,
            @Reps_ID,
            @UserID,
            AW_User_Companies_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @SoldConsignmentID        

    SELECT @DocumentID = Scope_Identity()

 --   --> Update the Customer Account Balance
	UPDATE AC_Customers
	SET Account_Balance = Account_Balance + @Total
	WHERE AC_Customers_ID = @CustomerID

	SELECT @Cost_Original = Total_Cost
	FROM AS_Transactions
    WHERE AS_Transactions_ID = @SoldConsignmentID
    
--Insert Into Temp_Debug Values('@SoldConsignmentID',Convert(Varchar(100),@SoldConsignmentID))   	

	DECLARE GetData CURSOR 
	FOR
		SELECT AS_Transaction_Details_ID, AP_Products_ID, Quantity, Date_Captured, Lup_AP_Product_Bins_ID
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @SoldConsignmentID
		ORDER BY AS_Transaction_Details_ID	
	
	OPEN GetData
	FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @AP_Products_ID, @Quantity, @Detail_Date_Captured, @ProductBinID
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @IsConsignmentStock = 0
		SET @Quantity_Cons = @Quantity * -1
	
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
	
--Insert Into Temp_Debug Values('41 - @Quantity_Cons',Convert(Varchar(100),@Quantity_Cons))   	
--Insert Into Temp_Debug Values('41 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
		
		EXEC sp_AS_Transaction_Detail_Consignment @AP_Products_ID, @Quantity_Cons, @UserID, @CompanyID, @IsConsignmentStock OUTPUT	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('41 - @ProductsQty After GRV',Convert(Varchar(100),@ProductsQty))   	
	
		--It does not matter if the the product is a consignment stock item. 
		--You still need to get the latest product cost
		--IF @IsConsignmentStock = 1
		--BEGIN
			
			SET @CostingMethod = 0
			SELECT @CostingMethod = Control_Index 
			FROM Sys_AW_Options 
			WHERE Control_Name = 'optInventoryValuation' 
			AND Control_Value = 'True'
		
			--0 - Average Cost
			--1	- Last Cost
			--2 - Standard Cost
			IF @CostingMethod IS NULL
				SET @CostingMethod = 0
				
			IF @CostingMethod = 0
			BEGIN
				SELECT @Cost = ISNULL(Average_Cost,0)
				FROM AP_Products
				WHERE AP_Products_ID = @AP_Products_ID
			END

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

		--V6.2 RL 2015-08-18 If the Cost has changed due to consignment stock being GRV into the system, Update Total Cost
		SET @Cost_Diff = 0
		SET @Cost_Diff = @Cost_Original - @Cost
		--IF @Cost_Diff <> 0
		--BEGIN
		--	UPDATE AS_Transactions
		--		SET Total_Cost = Total_Cost + (@Cost_Diff * @Quantity)
		--	WHERE AS_Transactions_ID = @DocumentID
		--END
				
--		IF @IsConsignmentStock = 0
--		BEGIN
			UPDATE AP_Products
			SET On_Hand = On_Hand + @Quantity,
				Last_Sale_Date = getdate(),
				[User_ID] = @UserID
			WHERE AP_Products_ID = @AP_Products_ID
		--END
		--ELSE
		--BEGIN
		--	UPDATE AP_Products
		--	SET Last_Sale_Date = getdate(),
		--		[User_ID] = @UserID
		--	WHERE AP_Products_ID = @AP_Products_ID		
		--END

		--V6.2 Update Bin Qty
		IF @Quantity <> 0
		BEGIN
			--SELECT @Quantity_Cons = @Quantity_Cons * -1
			
			EXEC sp_AP_Products_Bins_Update_Insert 
				@AP_Products_ID,	--@ProductID int,
				@ProductBinID,		--@ProductBinID int,
				@Quantity,		--@Qty decimal(9,3)
				'CON S',			--@Source varchar(10),
				0,					--@Batch_No
				@UserID,			--@UserID int,
				@CompanyID			--@CompanyID int			    	
		END	
		
--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('41 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	
				
		INSERT INTO AS_Transaction_Details
		(
			AS_Transactions_ID,
			AP_Products_ID,
			Quantity,
			Unit_Cost,
			Unit_Price,
			Original_Price,
			Discount_Amount,
			Tax_Amount,
			Extended_Amount,
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			User_ID,
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		)
		SELECT
			@DocumentID,
			AP_Products_ID,
			(Quantity*-1),
			@Cost, --Costing could have changed since it was sold on consignment note
			Unit_Price,
			Original_Price,
			(Discount_Amount*-1),
			(Tax_Amount*-1),
			(Extended_Amount*-1),
            AS_Job_References_ID,
            Make,
            Serial_No,
            Customer,
            Date_Captured,
			[User_ID],
			AW_User_Companies_ID,
			Lup_AP_Product_Bins_ID
		FROM AS_Transaction_Details
		WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID	
		
		SELECT @DocumentDetailsID = Scope_Identity()

		--V6.3 RL 2017-05-13 Recalc Header Totals
		SELECT @H_Total_Cost = SUM((Quantity + Back_Order) * Unit_Cost),
				@H_Total_Discount_Amount = SUM(Discount_Amount),
				@H_Amount = SUM(Extended_Amount - Tax_Amount),
				@H_Total_Tax_Amount = SUM(Tax_Amount),
				@H_Total_Amount = SUM(Extended_Amount)
		FROM AS_Transaction_Details
		WHERE AS_Transactions_ID = @DocumentID
		
		UPDATE AS_Transactions
		SET Total_Cost = @H_Total_Cost,
			Total_Discount_Amount = @H_Total_Discount_Amount,
			Amount = @H_Amount,
			Total_Tax_Amount = @H_Total_Tax_Amount,
			Total_Amount = @H_Total_Amount
		WHERE AS_Transactions_ID =  @DocumentID
		
		INSERT INTO AS_Transaction_Details_Consignment
		(		
			AS_Transaction_Details_ID, --Sys_AW_Transaction_Types_ID 33 Consignment Stock Note
			Consignment_ID,
			Sys_AW_Transaction_Types_ID,
			Quantity,
			Date_Captured,
			[User_ID],
			AW_User_Companies_ID	
		)
		VALUES
		(
			@ConsignmentID,
			@DocumentDetailsID,
			3,
			ABS(@Quantity),
			@Detail_Date_Captured,
			@UserID,
			@CompanyID
		)

		FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @AP_Products_ID, @Quantity, @Detail_Date_Captured, @ProductBinID
	END
	CLOSE GetData
	DEALLOCATE GetData


RETURN @DocumentID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Header_Consignment2
--Purpose       :Selects POS Transaction Header Shaped for Customer Consignment Stock
--Date          :2015/05/18
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Header_Consignment2]
	(
        @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 @SearchString <> ''
		BEGIN --@SearchString <> ''
--------------------------------------------->>>>>>>
			IF @Filter3 <> ''
			BEGIN --@Filter3 <> ''
				SET @Filter3 = '%' +  @Filter3 + '%'
				SET @Filter2 = '%' +  @Filter2 + '%'
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					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 [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.[Description] AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				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
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND
					(
						(t.Transaction_Number like @Filter1 AND
						 t.Transaction_Number like @Filter2 AND
						 t.Transaction_Number like @Filter3) OR
						 
						(p.Product_Code like @Filter1 AND
                         p.Product_Code like @Filter2 AND
                         p.Product_Code like @Filter3) OR

						(p.Description like @Filter1 AND
						 p.Description like @Filter2 AND
						 p.Description like @Filter3) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1 AND
						 ISNULL(t.Customer_Reference,'') like @Filter2 AND
						 ISNULL(t.Customer_Reference,'') like @Filter3)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter3 <> ''	 
			
			IF @Filter2 <> ''
			BEGIN --@Filter2 <> ''				
				SET @Filter2 = '%' +  @Filter2 + '%'
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					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 [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				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
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND					
					(
						(t.Transaction_Number like @Filter1 AND
						 t.Transaction_Number like @Filter2) OR
						 
						(p.Product_Code like @Filter1 AND
                         p.Product_Code like @Filter2) OR

						(p.Description like @Filter1 AND
						 p.Description like @Filter2) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1 AND
						 ISNULL(t.Customer_Reference,'') like @Filter2)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter2 <> ''	 
	
			IF @Filter1 <> ''
			BEGIN --@Filter1 <> ''				
				SET @Filter1 = '%' +  @Filter1 + '%'
                
                SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					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 [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
				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
					INNER JOIN AS_Transaction_Details td
						ON t.AS_Transactions_ID = td.AS_Transactions_ID
					INNER JOIN AP_Products p
						ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
				WHERE t.AW_User_Companies_ID = @CompanyID AND
					t.AC_Customers_ID = @CustomerID AND
					t.Sys_AW_Transaction_Types_ID = 33 AND
					(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
					DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0) AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND					
					(
						(t.Transaction_Number like @Filter1) OR
						 
						(p.Product_Code like @Filter1) OR

						(p.Description like @Filter1) OR

						(ISNULL(t.Customer_Reference,'') like @Filter1)
					) 						 
				ORDER BY t.Transaction_Date DESC
			END --@Filter1 <> ''	 
		END --@SearchString <> ''
		
--------------------------------------------->>>>>>>
		IF @SearchString = ''
		BEGIN --@SearchString = ''
--------------------------------------------->>>>>>>
                
            SELECT DISTINCT
					t.AS_Transactions_ID AS [ID],
					td.AS_Transaction_Details_ID AS [DetailID],
					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 [Tran No],
					t.Customer_Reference AS [Order No],
					p.Product_Code AS [Product Code],
					p.Description AS [Product Description],
					td.Quantity AS  [Quantity],
					dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID) AS [Invoiced Qty],
					dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Returned Qty],
					td.Quantity   
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) AS [Left],
					td.Unit_Price As [Unit Price],
					td.Discount_Amount AS [Discount],
					td.Tax_Amount AS [VAT],
					td.Extended_Amount AS [Total Amount],
					td.Unit_Cost  AS [Unit Cost],
					ISNULL(u.Firstname, '') + ISNULL(' ' + u.Surname, '') AS [User],
                    act.[Description] AS [Active],
                    t.Sys_AW_Transaction_Types_ID AS [TypeID],
                    p.Average_Cost As [Aver Cost],
                    p.AP_Products_ID AS [AP_Products_ID],
                    td.Unit_Price As [Cons Unit Price],
                    td.Discount_Amount AS [Cons Discount],
					td.Tax_Amount AS [Cons VAT],
					td.Extended_Amount AS [Total Cost],
					td.Unit_Cost  AS [Cons Unit Cost],
					td.Original_Price  AS [Original Price],
					tc.Tax_Rate AS [Tax Rate],
					ISNULL(t.Lup_AS_Reps_ID,1) AS [Sales_Rep_ID],
					ISNULL(r.[Description],'') AS [Sales Rep]
			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
				INNER JOIN AS_Transaction_Details td
					ON t.AS_Transactions_ID = td.AS_Transactions_ID
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = td.AP_Products_ID	    
					INNER JOIN Sys_AW_Tax_Codes tc
						ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
					LEFT OUTER JOIN Lup_AS_Reps r
						ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID						
			WHERE t.AW_User_Companies_ID = @CompanyID AND
				t.AC_Customers_ID = @CustomerID AND
				t.Sys_AW_Transaction_Types_ID = 33 AND
					td.Quantity 
								- dbo.fn_AP_Get_Consignment_Stock_Sold(AS_Transaction_Details_ID)
								- dbo.fn_AP_Get_Consignment_Stock_Returned(AS_Transaction_Details_ID) <> 0 AND				
				(DATEDIFF(d, t.Transaction_Date, @StartDate) <= 0 AND
				DATEDIFF(d, t.Transaction_Date, @EndDate) >= 0)
			ORDER BY t.Transaction_Date DESC
		END --@SearchString = ''
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_DayEnd_Performance]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Performance]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Performance
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--              :netted by Inter-Company by Filter
--Functionality :NB SP used by BOTH Sales Performae and Sales Performance with QTY
--Date          :2004/01/28
--Authors       :TB
--MODS:         :03/07/04 - Moved Lup_AC_Customer_Types_ID to Sys_AC_Account_Types_ID 
--              :           and replaced @CustType input parameter with @AccountType
--              :22/11/04 - Added ISNULL validation on all Numeric DB fields 
--              :03/05/05 - Added [Qty] and removed [TranDate] and [TranNo] (Protea)

--              :03/05/05 - Added 'Sales Person' filter (Protea)
--RL	V6.2	2016-06-24	:Add ISNULL check to Extended_Amount, Tax_Amount, Quantity And Unit_Cost
--RL	V6.2	2016-06-24	:Added Product Purchase Category group option
--RL	V6.2	2016-06-24	:Added Product Bin group option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Performance]
    (
        @Option_1 varchar(30),
        @Option_2 varchar(30),        
        @AccountType tinyint,
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(6000)

-- SET @Option = 'Bin'
-- SET @AccountType = 0
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    SET @sql = @sql + ' d.AW_User_Companies_ID AS [CompanyID], '

	--@Option_1
    IF @Option_1 = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Group'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Option_1 = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Purchase Category'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Bin'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Bins_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option_1 = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

	--@Option_2
    IF @Option_2 = 'Type'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Types_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Group'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Groups_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Department'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Departments_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Supplier'
        SET @sql = @sql +
            ' x.AO_Suppliers_ID AS [HeaderID_2], ' +
            ' x.[Supplier_Name] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Manufacturer'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Manufacturers_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Location'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Locations_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Purchase Category'
        SET @sql = @sql +
            ' x.Lup_AP_Purchase_Categories_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Bin'
        SET @sql = @sql +
            ' x.Lup_AP_Product_Bins_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Sales Area'
        SET @sql = @sql +
            ' x.Lup_AC_Sales_Areas_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = 'Sales Person'
        SET @sql = @sql +
            ' x.Lup_AS_Reps_ID AS [HeaderID_2], ' +
            ' x.[Description] AS [Filter_2], '
    ELSE
    IF @Option_2 = '<None>'
        SET @sql = @sql +
--            ' o.Lup_AS_Reps_ID AS [HeaderID_2], ' +
--            ' o.[Description] AS [Filter_2], '

            ' 0 AS [HeaderID_2], ' +
            ''' <None>''' + ' AS [Filter_2], '



    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 + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) AS [TotalSales], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN ISNULL(ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), 0) '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + '      END AS [InterCo], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN 0 '
    SET @sql = @sql + '      ELSE ISNULL(ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), 0) '
    SET @sql = @sql + '      END AS [NetSales], '

    SET @sql = @sql + ' CONVERT(money, (ISNULL(d.Extended_Amount,0) - ISNULL(d.Tax_Amount,0)) - (ISNULL(d.Quantity,0) * ISNULL(d.Unit_Cost,0))) AS [TotalGP], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN CONVERT(money, (ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) - (ISNULL(d.Quantity, 0) * ISNULL(d.Unit_Cost, 0))) '
    SET @sql = @sql + '      ELSE 0 '
    SET @sql = @sql + '      END AS [InterCoGP], '

    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 3 '
    SET @sql = @sql + '      THEN 0 '
    SET @sql = @sql + '      ELSE CONVERT(money, (ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) - (ISNULL(d.Quantity, 0) * ISNULL(d.Unit_Cost, 0))) '
    SET @sql = @sql + '      END AS [NetGP], '

    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(ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0), ISNULL(d.Quantity,0), ISNULL(d.Unit_Cost,0))) / dbo.fn_AS_Calc_Act_Sales_Value(ISNULL(d.Extended_Amount,0), ISNULL(d.Tax_Amount,0)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [TotGP%], '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(ISNULL(d.Original_Price,0), ISNULL(d.Unit_Cost,0), ISNULL(d.Quantity,0))) / dbo.fn_AS_Calc_Std_Sales_Value(ISNULL(d.Original_Price,0), ISNULL(d.Quantity,0)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [StdGP%], '

    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0)) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, ISNULL(d.Original_Price, 0) * ISNULL(d.Quantity, 0)) AS [Selling], '

    SET @sql = @sql + ' ISNULL(d.Quantity, 0) AS [Qty], '

    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    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 '

	--@Option_1
    IF @Option_1 = 'Type'
        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 @Option_1 = 'Group'
        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 @Option_1 = 'Department'
        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 @Option_1 = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option_1 = 'Manufacturer'
        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 @Option_1 = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option_1 = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option_1 = 'Bin'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins o ' +
            '        ON d.Lup_AP_Product_Bins_ID = o.Lup_AP_Product_Bins_ID '
    ELSE
    IF @Option_1 = 'Sales Area'
        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 @Option_1 = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

	--@Option_2
    IF @Option_2 = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types x ' +
            '        ON p.Lup_AP_Product_Types_ID = x.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option_2 = 'Group'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups x ' +
            '        ON p.Lup_AP_Product_Groups_ID = x.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option_2 = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments x ' +
            '        ON p.Lup_AP_Product_Departments_ID = x.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option_2 = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers x ' +
            '        ON p.Default_Supplier_ID = x.AO_Suppliers_ID '
    ELSE
    IF @Option_2 = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers x ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = x.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option_2 = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations x ' +
            '        ON p.Lup_AP_Product_Locations_ID = x.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option_2 = 'Purchase Category'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Purchase_Categories x ' +
            '        ON p.Lup_AP_Purchase_Categories_ID = x.Lup_AP_Purchase_Categories_ID '
    ELSE
    IF @Option_2 = 'Bin'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Bins x ' +
            '        ON d.Lup_AP_Product_Bins_ID = x.Lup_AP_Product_Bins_ID '
    ELSE
    IF @Option_2 = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas x ' +
            '        ON c.Lup_AC_Sales_Areas_ID = x.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option_2 = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps x ' +
            '        ON c.Lup_AS_Reps_ID = x.Lup_AS_Reps_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 @AccountType <> 0        --0 = ALL Account Types
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID = ' + CONVERT(varchar(10), @AccountType) + ' '
        END

	--IF @Option_2 = '<All>'
	--    SET @sql = @sql + ' ORDER BY [Filter], [Product], [TranDate] '
	--Else
		SET @sql = @sql + ' ORDER BY [Filter_2], [Filter], [Product], [TranDate] '    

--Select @sql

EXEC (@sql)
GO
--Insert Consignment Stock Adjustment Types Types
IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AP_Adjustment_Types
	WHERE [Description] = 'Consignment Received'
) 
BEGIN
	INSERT Sys_AP_Adjustment_Types
	(		
		[Description]
	)
	VALUES
	(
		'Consignment Received'
	)
END
GO

IF NOT EXISTS
(
	SELECT 1
	FROM Sys_AP_Adjustment_Types
	WHERE [Description] = 'Consignment Returned'
) 
BEGIN
	INSERT Sys_AP_Adjustment_Types
	(		
		[Description]
	)
	VALUES
	(
		'Consignment Returned'
	)
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Product_Cardex]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Product_Cardex]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Cardex
--Purpose       :Retrieves Inventory physical movement
--Functionality :    uses UNION ALL
--Date          :2004/10/10
--Authors       :TB
--MODS:         :12/05/05 - Appended (AO_GRV_ID) to Supplier_Reference
--2004.3.4      :08/03/07 - Replaced gh.Supplier_Reference with
--              :           gh.Delivery_Note_Number to show Supplier Invoice Number
--2004.3.9      :13/06/08 - Changed [Supplier/Customer] field in ADJUSTMENTS section
--              :           and inserted [Note] from AP_Inventory_Adjustments table
--2004.4.2      :23/10/08 - Change SALES section from Sales Cost to Selling Price - RM
--              :           and renamed aliases [Unit Cost] to [Unit Price]
--              :           and [Total Cost] to [Total]
--2004.4.7      :12/09/09 - Added STOCK TRANSFER type in SALES section
--2004.4.9      :03/10/10 - Fixed STOCK TRANSFER type in SALES section. OMITTED to
--              :           add h.Sys_AW_Transaction_Types_ID = 23 in WHERE clause !!!!!
--              :03/10/10 - Added split STOCK TRANSFER types in SALES section
--              :           into 'TRF IN' and 'TRF OUT' based on d.Quantity value
--2004.5.1      :02/06/11 - Added h.Sys_AW_Transaction_Types_ID = 29 as 'GRVFAC'
--              :           in GOODS RECEIVED for Casing Tracking Factory GRV's
--              :15/06/11 - Added h.Sys_AW_Transaction_Types_ID = 23 as 'TRF IN/OUT'
--              :           in SALES section WHERE clause
--2004.5.2      :06/07/11 - Added h.Sys_AW_Transaction_Types_ID = 30 as 'GRNFAC'
--              :           in GOODS RETURNED for Casing Tracking Factory CLAIM REFUND
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 31 as 'CRV' and 
--              :            h.Sys_AW_Transaction_Types_ID = 32 as 'CRN' for consignment stock
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 33 as 'CON N' and 
--							h.Sys_AW_Transaction_Types_ID = 34 as 'CON S' and 
--              :           h.Sys_AW_Transaction_Types_ID = 35 as 'CON R' for consignment stock sales
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Cardex]
    (
        @StartDate as datetime,
        @ProductID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql			varchar(8000)
    DECLARE @DefaultBin		varchar(50)

-- SET @StartDate = '2004/09/01 00:00:01'
-- SET @ProductID = 271

	SELECT @DefaultBin = [Description]
	FROM Lup_AP_Product_Bins
	WHERE Lup_AP_Product_Bins_ID = 1

	IF ISNULL(@DefaultBin,'') = ''
		SET @DefaultBin = '<None>'

-------------------------------------------------------------------------------
-- GOODS RECEIVED
-------------------------------------------------------------------------------

    SET @sql = ' SELECT '

    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), gh.Date_Received, 121)) AS [Date], '
    SET @sql = @sql + '     ISNULL(gh.Delivery_Note_Number, '''') '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), gh.AO_GRV_ID) + '')'' AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    --GRVs always done to and from default bin
    SET @sql = @sql + '''' + @DefaultBin + '''' + ' AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN gh.Sys_AW_Transaction_Types_ID = 19 '
    SET @sql = @sql + '          THEN ''GRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 20 '
    SET @sql = @sql + '          THEN ''RETURN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '          THEN ''GRVFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 30 '
    SET @sql = @sql + '          THEN ''GRNFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 31 '
    SET @sql = @sql + '          THEN ''CRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 32 '
    SET @sql = @sql + '          THEN ''CRN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 34 '
    SET @sql = @sql + '          THEN ''CON S'' '                
    SET @sql = @sql + '          ELSE ''NOGRV'' '
    SET @sql = @sql + '     END AS [Type], '

    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.Net_Amount, 0) AS [Total], '
    SET @sql = @sql + '     gd.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
    SET @sql = @sql + '         ON p.AP_Products_ID = gd.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_GRV gh '
    SET @sql = @sql + '         ON gd.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON gh.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND gd.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 20 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 29 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 30 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 31 ' + ' '        
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 32 ' + ' '            
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 34) ' + ' '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- ADJUSTMENTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.AP_Inventory_Adjustments_ID) AS [Ref No], '
    SET @sql = @sql + '     ISNULL(a.Note, '''') AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     CASE WHEN a.Sys_AP_Adjustment_Types_ID = 1 '
    SET @sql = @sql + '          THEN ''ADJUST'' '
    SET @sql = @sql + '          WHEN a.Sys_AP_Adjustment_Types_ID = 6 '
    SET @sql = @sql + '          THEN ''TAKEON'' '
    SET @sql = @sql + '          ELSE ''NOADJ'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ISNULL(a.New_Last_Cost, 0) AS [Unit Price], '
    SET @sql = @sql + '     ROUND((ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0)) * ISNULL(a.New_Last_Cost, 0), 2) AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Inventory_Adjustments a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
    SET @sql = @sql + '     OR a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
    SET @sql = @sql + '   AND ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) <> 0 ' + ' '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), h.Transaction_Date, 121)) AS [Date], '
    SET @sql = @sql + '     h.Transaction_Number AS [Ref No], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, ''''))) AS [Supplier/Customer], '
	SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''SALE'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''REFUND'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) < 0) '
    SET @sql = @sql + '          THEN ''TRF IN'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) >= 0) '
    SET @sql = @sql + '          THEN ''TRF OUT'' '    
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 33  '
    SET @sql = @sql + '          THEN ''CON N'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 34  '
    SET @sql = @sql + '          THEN ''CON S'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 35  '
    SET @sql = @sql + '          THEN ''CON R'' '
    SET @sql = @sql + '          ELSE ''NOSALE'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     (ISNULL(d.Quantity, 0) * -1) AS [Qty], '

    SET @sql = @sql + '     CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '          THEN ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) / ISNULL(d.Quantity, 0), 2) '
    SET @sql = @sql + '          ELSE 0 '
    SET @sql = @sql + '     END AS [Unit Price], '

    SET @sql = @sql + '     ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)), 2) AS [Total], '
    SET @sql = @sql + '     d.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AC_Customers c '
    SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON d.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND d.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 23 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 33 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 34 OR '            
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 35) '

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations From Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     ISNULL(a.From_Bin_New_On_Hand, 0) - ISNULL(a.From_Bin_Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.From_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations To Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '

    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     ISNULL(a.To_Bin_New_On_Hand, 0) - ISNULL(a.To_Bin_Previous_On_Hand, 0) AS [Qty], '
    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.To_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' ORDER BY [CompanyID], [Date Captured] '

--PRINT @sql

EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Replenish_Analysis
--Purpose       :Inventory Replenishment Analysis with Last 6 months Sales Analysis
--Date          :2010/01/28
--Authors       :TB
--MODS:         :
--2004.5.4      :20/09/11 - Added @StartMonth and [Current] field as Current Month sales
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis]
    (
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @CompanyID int,
        @M1 varchar(6),
        @M2 varchar(6),
        @M3 varchar(6),
        @M4 varchar(6),
        @M5 varchar(6),
        @M6 varchar(6),
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
      	@LocationID int = -1,
      	@PurchCatID int = -1
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Filter varchar(4000),
            @StartMonth datetime


	SET @Filter = ''
    SET @sql = ''


    -- FIRST day of the @EndDate month
    SET @StartMonth = CONVERT(datetime, CONVERT(varchar(4), YEAR(@EndDate)) + '/' + CONVERT(varchar(2), MONTH(@EndDate)) + '/' + '01 00:00:01' )


    SET @Filter = ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @Filter = @Filter + '  AND (h.Date_Captured >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @Filter = @Filter + '  AND  h.Date_Captured <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @Filter = @Filter + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @Filter = @Filter + '       h.Sys_AW_Transaction_Types_ID = 4)'


    --> Supplier
	IF @SupplierID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                        convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                        convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0
		BEGIN
    		SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                        convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0
		BEGIN
			SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                        convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                        convert(varchar(20), @DepartmentID)
		END
    --> Location
	IF @LocationID  > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                        convert(varchar(20), @LocationID)
    	END
    --> PurchCat
	IF @PurchCatID  > 0
		BEGIN
            SET @Filter = @Filter + ' AND p.Lup_AP_Purchase_Categories_ID = ' +
                                        convert(varchar(20), @PurchCatID)
    	END


    SET @sql = ' SELECT DISTINCT '
    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [UnitPrice], '
    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '
    SET @sql = @sql + ' p.Average_Cost AS [AvgCost], '
    SET @sql = @sql + ' CASE WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
    SET @sql = @sql + '      THEN ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - p.Last_Cost) / dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [LastDisc%], '
    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date, 121) AS [LastSale], '
    SET @sql = @sql + ' p.On_Hand AS [On Hand], '

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN	
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN		
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN			
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN				
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN					
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	
	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN							
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.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 + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '


    SET @sql = @sql + @Filter


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


    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_Active_ID = 1 '
        END


    IF @ExclInterCo = 1      --Exclude Inter-Company sales
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Product] '
        END

--PRINT @sql

EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Replenish_Analysis2
--Purpose       :Inventory Replenishment Analysis with Last 6 months Sales Analysis
--              :    by Product Filter
--Date          :2010/06/08
--Authors       :TB
--MODS:         :
--2004.5.4      :20/09/11 - Added @StartMonth and [Current] field as Current Month sales
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Replenish_Analysis2]
	(
        @StartDate datetime,
        @EndDate datetime,
        @SortOrder tinyint,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @ExclInterCo tinyint,
        @CompanyID int,
        @M1 varchar(6),
        @M2 varchar(6),
        @M3 varchar(6),
        @M4 varchar(6),
        @M5 varchar(6),
        @M6 varchar(6),
        @Filter varchar(100)
	)

AS

SET NOCOUNT ON


    DECLARE @sql varchar(8000),
            @Where varchar(4000),
            @StartMonth datetime


	SET @Where = ''
    SET @sql = ''


    -- FIRST day of the @EndDate month
    SET @StartMonth = CONVERT(datetime, CONVERT(varchar(4), YEAR(@EndDate)) + '/' + CONVERT(varchar(2), MONTH(@EndDate)) + '/' + '01 00:00:01' )


    SET @Where = ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @Where = @Where + '  AND (h.Date_Captured >= ''' + CONVERT(varchar(30), @StartDate) + ''' '
    SET @Where = @Where + '  AND  h.Date_Captured <= ''' + CONVERT(varchar(30), @EndDate) + ''') '
    SET @Where = @Where + '  AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @Where = @Where + '       h.Sys_AW_Transaction_Types_ID = 4)'
    
    
    SET @sql = ' SELECT DISTINCT '

    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'PurchCat'
        SET @sql = @sql +
            ' o.Lup_AP_Purchase_Categories_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' p.AP_Products_ID as [ID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [UnitPrice], '
    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '
    SET @sql = @sql + ' p.Average_Cost AS [AvgCost], '
    SET @sql = @sql + ' CASE WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
    SET @sql = @sql + '      THEN ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - p.Last_Cost) / dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()) * 100) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [LastDisc%], '
    SET @sql = @sql + ' CONVERT(CHAR(10), p.Last_Sale_Date, 121) AS [LastSale],  '
    SET @sql = @sql + ' p.On_Hand AS [On Hand], '

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M1 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M1], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN	
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M2 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M2], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M3 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M3], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M4 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M4], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M5 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M5], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) = ''' + @M6 + ''' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Date_Captured) '
		SET @sql = @sql + ' ), 0) AS [M6], '	
	END

	IF @ExclInterCo = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' INNER JOIN AC_Customers x '
		SET @sql = @sql + ' ON x.AC_Customers_ID = f.AC_Customers_ID '		
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + ' x.Sys_AC_Account_Types_ID <> 3 AND '		
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(e.Quantity) '
		SET @sql = @sql + ' FROM AS_Transaction_Details e '
		SET @sql = @sql + ' INNER JOIN AS_Transactions f '
		SET @sql = @sql + ' ON f.AS_Transactions_ID = e.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE e.AP_Products_ID = p.AP_Products_ID AND '
		SET @sql = @sql + '   f.Date_Captured BETWEEN ' + '''' + CONVERT(varchar(30), @StartMonth) + '''' + ' AND ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' AND '
		SET @sql = @sql + '  (f.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '   f.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + ' ), 0) AS [Current] '
	END

    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.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 + '     LEFT JOIN AC_Customers c '
    SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '


    IF @Filter = 'Type'
        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 @Filter = 'Groups'
        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 @Filter = 'Department'
        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 @Filter = 'Supplier'
        SET @sql = @sql +
            ' LEFT JOIN AO_Suppliers o ' +
            '     ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        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 @Filter = 'Location'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Product_Locations o ' +
            '     ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'PurchCat'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AP_Purchase_Categories o ' +
            '     ON p.Lup_AP_Purchase_Categories_ID = o.Lup_AP_Purchase_Categories_ID '


    SET @sql = @sql + @Where


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


    IF @ActiveOnly = 1      --Active Products only
        BEGIN
            SET @sql = @sql + '  AND p.Slu_AW_Active_ID = 1 '
        END


    IF @ExclInterCo = 1      --Exclude Inter-Company sales
        BEGIN
            SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @SortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END
    ELSE
    IF @SortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Product] '
        END


    EXEC (@sql)



SET NOCOUNT OFF	
GO
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
-------------------------------------------------------------------------------
--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
--V6.2 RL	2015-06-09	:Removed inserting default print description
--						 From V6.0 If Print Description is blank, normal description is used
--V6.2	RL	2015-12-02	:Insert Default Bin location for new products
--V6.2	RL	2016-04-08	:A new product will be created if disabled products are not checked
-------------------------------------------------------------------------------

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

	IF @Price1Date = '1900-01-01'
	BEGIN
		SET @Price1Date = NULL
	END
	
	IF @Price2Date = '1900-01-01'
	BEGIN
		SET @Price2Date = NULL
	END
	
    ---------------------------------------------------------
    --> FIND the ID of the LOOKUP if ACTIVE or INSERT NEW
    ---------------------------------------------------------
    --> Get Manufacturer ID
    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

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

	--V6.3
	--Best of both worlds implemented. 
	--First check is on Product Code and Manufacturer,
	--Second. If it did not find a product useing the first check it will use the 
	--second checked based on Product Code and Date Captured. This was TB's method.
	--NB NB. Date Captured can not be used as a modified date. Second check would fail then!!!!!!!!

    ---------------------------------------------------------
    --> 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 V6.2 Product should be unique depending on Product Code and Manufacturer
      AND m.Description = @Manuf --This was commented out in V6.2 WTF!!!!
      --V6.2 RL 2016-04-08 A new product will be created if disabled products are not checked
      --AND p.Slu_AW_Active_ID = 1

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

	--V6.3 RL 2017-05-16 Added this back for Mertin at tyres 2000
	IF ISNULL(@ProductID,0) = 0
	BEGIN
		SELECT @ProductID = AP_Products_ID
		FROM AP_Products
		WHERE Product_Code = @ProductCode
			AND CONVERT(CHAR(19), Date_Captured) = CONVERT(CHAR(19), @DateCaptured)
			--AND Slu_AW_Active_ID = 1
	END

    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
						Date_Captured = @DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
                        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
					IF ISNULL(@ProductCode,'') <> ''
					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), From V6.0 If Print Description is blank, normal description is used
								@ProductCode,
								@Size,
								@DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
								--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
						
						--V6.2 Update Bin Qty
						--Done via trigger
						--INSERT INTO AP_Products_Bins
						--(
						--	AP_Products_ID, 
						--	Lup_AP_Product_Bins_ID, 
						--	On_Hand, 
						--	Date_Captured, 
						--	[User_ID], 
						--	AW_User_Companies_ID, 
						--	Slu_AW_Active_ID
						--)
						--Values
						--(
						--	@ProductID,
						--	1,
						--	0,
						--	GETDATE(),
						--	@UserID,
						--	@CompanyID,
						--	1							
						--)
					END
                END
        END
    ELSE
        BEGIN
            IF @ProductID > 0
                BEGIN
                    UPDATE AP_Products
                    SET Description = @Description,
                        --Date_Captured = @DateCaptured, --RL V6.0
						Date_Captured = @DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
                        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
   					IF ISNULL(@ProductCode,'') <> ''
					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), From V6.0 If Print Description is blank, normal description is used
								@ProductCode,
								@Size,
								@DateCaptured, --RL V6.3 Moved back for Tyes 2000 Mertin
								--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
						
						--V6.2 Update Bin Qty
						--Done via trigger
						--INSERT INTO AP_Products_Bins
						--(
						--	AP_Products_ID, 
						--	Lup_AP_Product_Bins_ID, 
						--	On_Hand, 
						--	Date_Captured, 
						--	[User_ID], 
						--	AW_User_Companies_ID, 
						--	Slu_AW_Active_ID
						--)
						--Values
						--(
						--	@ProductID,
						--	1,
						--	0,
						--	GETDATE(),
						--	@UserID,
						--	@CompanyID,
						--	1							
						--)
						
					END
                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
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Qty]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Qty]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Qty
--Purpose       :Returns stock quantity on consignment
--Parameters    :
--Date          :2015/04/14
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

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

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ISNULL(SUM(Qty), 0)
            FROM AO_GRV a
                INNER JOIN AO_GRV_Details d
                    ON a.AO_GRV_ID = d.AO_GRV_ID
            WHERE d.AP_Products_ID = @ProductID AND
				  a.Sys_AW_Transaction_Types_ID in (31, 32, 33, 34, 35) AND	
                  d.Slu_AW_Active_ID = 1 AND
                  a.Slu_AW_Active_ID = 1

    	RETURN @Qty
    END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Day_End]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Day_End]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Day_End
--Purpose       :Daily Sales Day-End procedure
--              :Inserts GL Journal and GL Transactions to GL CONTROL ACCOUNTS:
--              :1. DEBTORS, SALES, & VAT CONTROL
--              :2. RECEIPTS to DEBTORS & CASH CONTROL
--              :3. INTEREST JOURNALS to DEBTORS & INTEREST RECEIVED - Removed 31/05/04
--              :4. SETTLEMENT DISCOUNT to DEBTORS & SETTLEMENT DISCOUNT ALLOWED
--              :    for the following AS_Transaction_Types:
--              :        3=Invoice, 4=Refund, 7=Receipt,
--              :        15=Interest Journal, 18=Settlement Discount
--              :
--              :Ignores 5=Customer Journals. This is updated in Customer Journals
--              :-------------------------------------------------------
--              :GL Transaction Ref no's: !! REDUNDANT 15/10/03 !!
--              :Sales:            Debtors = 90, Sales = 91, VAT = 92
--              :Cost Of Sales:    Cost Of Sales = 82, Inventory = 83
--              :Receipts:         Debtors = 93, Cash = 94
--              :Interest:         Debtors = 95, Interest Received = 96 - Removed 31/05/04
--              :Settlement:       Debtors = 97, Discount Allowed = 98
--              :-------------------------------------------------------
--Date          :2002/02/06
--Authors       :TB
--MODS          :07/07/02 - Inserted VAT on Settlement Discount transaction
--              :07/07/02 - Changed Sys_AB_Transaction_Types_ID for each TranType
--              :19/07/02 - Added RECEIPTS TranTypes 21 (Back Office Receipt) and
--              :           22 (EFT Receipt) and split RECEIPTS updates to GL
--              :28/09/02 - Removed @Date parameter passed in from UI and replaced
--              :           it with @DayEndDate (SERVER date) to eliminate DE's
--              :           on different computers with varying Realtime Clock
--              :21/12/02 - Modified @GLControlAccount def from smallint to int
--              :04/09/03 - Added to Post Day-End COST OF SALES to Inventory/C.O.S.
--              :           if chkGRVtoInventoryCOS parameter is vbChecked
--              :15/10/03 - Replaced ALL GL Transaction Ref no's number and apply
--              :           @NextGLTranID reference number to ALL GL Transactions
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :31/05/04 - Removed Customer Interest updated here in Day-End.
--              :           Customer Interest update was removed and put back into 
--              :           sp_AC_Customer_Journals_Insert_Update on 28/07/02 !!
--2004.2.4      :04/06/05 - Added filter @CompanyID in ALL WHERE clauses !!!!!!
--              :05/06/05 - Added fetch PICKLIST from NEW AS_Day_Ends table
--              :05/06/05 - Added INSERT NEW AS_Day_Ends table
--2004.2.7      :28/03/06 - Replaced GL TranType 24 (Accounts Receivable - Settlement)
--              :           with GL TranType 22 (Accounts Receivable - Journal)
--              :           for Settlement Discount portion of Day-End procedure
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.6      :08/08/09 - Added UPDATE DAY-END FLAG in NEW AS_Till_Payouts table
--2004.5.3      :09/08/11 - Added Day-End CUTOFF DATE using Transaction_Date and DELETE DAY-END
--2004.5.5      :10/11/11 - Added Set @RetVal = 1 in DO DAY-END when Day-End completed succesfully
--2004.5.7 RGL  :2012-10-22 - Split Levy product transactions to Sales and COS GL 
--                            accounts as setup on Products
--2004.6.2 RGL  :2015-07-02 - Added Consignment GL entries
--2004.6.2 RGL  :2015-08-07 - Added Call to sp_AS_Day_End_Summary. Writes to Day End Summary tables
--2004.6.2 RGL  :2015-08-07 - Changed @DayEndDate from DateTime to SmallDateTime
--2016.6.2 RGL	:2016-08-04	:Changed Settlement discount from 22 to 24 ABTranType - AP Settlement
--							 So that it shows in its own section on TAX report
-------------------------------------------------------------------------------
---- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
--2004.2.5      :23/10/05 - Added to each Product Sales and C.O.S. GL Accounts using
--              :           System Options chkUseProductSalesGL and chkUseProductCOSGL
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_Day_End]
	(
		@Choice int,
		@CompanyID int,
		@Month tinyint,
		@Year int,
        @UserID int,
        @CutOffDate datetime
	)
AS
SET NOCOUNT ON

	DECLARE --@DayEndDate SmallDateTime, --DateTime, V6.2 Changed to match AS_Day_Ends and AS_Transactions Day_End field !!!Check
			@DayEndDate DateTime,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @DayEndCheck DateTime,
            @RetVal int,
            @SumAmount money,
            @SumTax money,
            @SumTotalAmount money,
            @SumTotalCost money,
            @GLControlAccount int,
            @SalesAmount money,
            @TaxAmount money,
            @Count int,
            @POSCount int,
            @BOFCount int,
            @EFTCount int,
            @InsertGLTran bit,
            @Settlement_Disc_Allowed_GL_ID int,
            @Settlement_Ex_VAT money,
            @Settlement_VAT money,
            @POSReceipts money,
            @BOFReceipts money,
            @EFTReceipts money,
            @TaxRate decimal(5,2),
            @GRInventoryCOS varchar(10),
            @PostGLSales varchar(10),
            @PostGLCOS varchar(10),

			@Levy_SumTax money,
			@Levy_SumTotalAmount money,
			@Levy_SumTotalCost money,
			@Levy_Count int,
			@NONLevy_SumTax money,
			@NONLevy_SumTotalAmount money,
			@NONLevy_SumTotalCost money,
			@NONLevy_Count int,
			@Levy_GRInventoryCOS_ID int,
            @Levy_PostGLSales_ID int,
            @Levy_PostGLCOS_ID int,
            @Levy_AP_Products_ID int,
            
			@SumConsignmentTax money,
            @SumConsignmentTotalAmount money,
            @SumConsignmentTotalCost money

	SET @DayEndDate = @CutOffDate    -- NEW 2004.5.3
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0            --0 = Do Not insert a GL Transaction in JNL Details
    SET @Count = 0
	SET @RetVal = 0
	SET @Levy_Count = 0
	SET @NONLevy_Count =0
	
	IF @Choice = 0    --Select list of PREVIOUS DAY-ENDS (PICKLIST)
	BEGIN
		SELECT AS_Day_Ends_ID AS [ID],
               Day_End,
               AB_Transaction_Ref AS [GL Tran Ref],
               AB_Transaction_Date AS [GLTranDate]
        FROM AS_Day_Ends
        WHERE AW_User_Companies_ID = @companyID
        ORDER BY Day_End DESC
	END

	ELSE
	IF @Choice = 1    --Do a NEW DAY-END
	BEGIN
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		BEGIN TRANSACTION

    --> SALES--------------------------------------------------------------

            SET @SumTax = 0
            SET @SumTotalAmount = 0
            SET @SumTotalCost = 0
            SET @Count = 0
            SET @Levy_SumTax = 0
            SET @Levy_SumTotalAmount = 0
            SET @Levy_SumTotalCost = 0
            SET @Levy_Count = 0
            SET @NONLevy_SumTax = 0
            SET @NONLevy_SumTotalAmount = 0
            SET @NONLevy_SumTotalCost = 0
            SET @NONLevy_Count = 0

        --> Get SALES
			SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                   @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                   @SumTotalCost = ISNULL(SUM(Total_Cost), 0),
                   @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL
              AND Transaction_Date <= @CutOffDate

            SET @SumTax = ROUND(@SumTax, 2)
            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)
            SET @SumTotalCost = ROUND(@SumTotalCost, 2)

        --> Get LEVY SALES
			SELECT @Levy_Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions t
			Inner Join AS_Transaction_Details d On
				t.AS_Transactions_ID = d.AS_Transactions_ID
			Inner Join AP_Products p On
			  	d.AP_Products_ID = p.AP_Products_ID
            WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  t.Day_End IS NULL AND
				  t.Transaction_Date <= @CutOffDate AND
				  p.Slu_AW_YesNo_Levy_Item = 1


        --> Get NON LEVY SALES
--			IF @Levy_Count < 0
--			BEGIN
				SELECT 
					@NONLevy_SumTax = ISNULL(SUM(Tax_Amount), 0),
					@NONLevy_SumTotalAmount = ISNULL(SUM(Extended_Amount), 0),
					@NONLevy_SumTotalCost = Cast( SUM( ISNULL(d.Unit_Cost,0) * ISNULL(d.Quantity,0) ) As Money),
					@NONLevy_Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions t
				Inner Join AS_Transaction_Details d On
					t.AS_Transactions_ID = d.AS_Transactions_ID
				Inner Join AP_Products p On
			  		d.AP_Products_ID = p.AP_Products_ID
				WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
					 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
					  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
					  t.Day_End IS NULL AND
					  t.Transaction_Date <= @CutOffDate AND
					  p.Slu_AW_YesNo_Levy_Item = 0

				SET @NONLevy_SumTax = ROUND(@NONLevy_SumTax, 2)
				SET @NONLevy_SumTotalAmount = ROUND(@NONLevy_SumTotalAmount, 2)
				SET @NONLevy_SumTotalCost = ROUND(@NONLevy_SumTotalCost, 2)
--			END

            IF @Count > 0 --If SALES transactions exist
            BEGIN

            --> Get 'Post GL SALES in Day-End to each Product's Sales GL Account' parameter
                SELECT @PostGLSales = RTRIM(LTRIM(Control_Value))
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkUseProductSalesGL' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID
				
				--If Levy transactions exist, then assign the NON Levy totals
				--to the normal variables and process as normaly
				IF @Levy_Count > 0
				BEGIN
					SET @SumTax = @NONLevy_SumTax
					SET @SumTotalAmount = @NONLevy_SumTotalAmount
					SET @SumTotalCost = @NONLevy_SumTotalCost             
				END				
				
				SET @Narration = 'Day End - Sales'

			--> Create NORMAL JOURNAL header for the Sales Journal
				IF @NextGLTranID = 0
				BEGIN

 					EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
							22,
							@CompanyID
    
					EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
							@DayEndDate,
							@NextGLTranID,
							@Narration,
							@Month,
							@Year,
							@UserID,
							@CompanyID

				END

			--> Update DEBTORS CONTROL
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 101    --Debtors Control

			--> Create JOURNAL DETAIL for Debtors Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@SumTotalAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for Debtors Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'101 Debtors',
						@Month,
						@Year,
						@NextGLTranID,
						@SumTotalAmount,
						@UserID,
						@CompanyID

			--> Reverse signs to balance double entry
				SET @SalesAmount = (@SumTotalAmount - @SumTax) * -1
				SET @TaxAmount = @SumTax * -1

			--> Update SALES CONTROL
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 102    --Sales Control

			--> Create JOURNAL DETAIL for Sales Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@SalesAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for Sales Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'102 Sales',
						@Month,
						@Year,
						@NextGLTranID,
						@SalesAmount,
						@UserID,
						@CompanyID

			--> UPDATE GL - VAT Control
				SELECT @GLControlAccount = AB_Accounts_ID
				FROM AB_Control_Accounts
				WHERE Control_Number = 401    --VAT Control

				SET @Narration = 'Day End - VAT on Sales'

			--> Create JOURNAL DETAIL for VAT Control
				EXEC sp_AB_Insert_Journal_Detail
						@JNLHeaderID,
						@GLControlAccount,
						@TaxAmount,
						@Narration,
						@UserID,
						@CompanyID,
						@InsertGLTran

			--> Create GL TRANSACTION for VAT Control
				EXEC sp_AB_Insert_GL_Transactions
						@Narration,
						22,
						@GLControlAccount,
						@DayEndDate,
						'401 VAT on Sales',
						@Month,
						@Year,
						@NextGLTranID,
						@TaxAmount,
						@UserID,
						@CompanyID

				SET @Count = 0

--> COST OF SALES -----------------------------------------------------

			--> Get parameter 'Post GL COST-OF-SALES in Day-End to each Product's Cost-of-Sales GL Account'
				SELECT @PostGLCOS = RTRIM(LTRIM(Control_Value))
				FROM Sys_AW_Options
				WHERE Control_Type = 'CheckBox' AND
					  Control_Name = 'chkUseProductCOSGL' AND
					  Control_Index = 0 AND
					  AW_User_Companies_ID = @CompanyID


			--> Get parameter 'Post directly to Inventory and Cost-of-Sales accounts  (Continous Inventory method)
				SELECT @GRInventoryCOS = RTRIM(LTRIM(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

--------------------------------------------------------------------------------------------
-- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
--------------------------------------------------------------------------------------------

					SET @Narration = 'Day End - Cost Of Sales'
    
				--> Create NORMAL JOURNAL header for Cost Of Sales
					IF @NextGLTranID = 0
					BEGIN

     					EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
								22,
								@CompanyID
        
    					EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
								@DayEndDate,
								@NextGLTranID,
								@Narration,
								@Month,
								@Year,
								@UserID,
								@CompanyID

					END
    
				--> Update COST OF SALES CONTROL
					SELECT @GLControlAccount = AB_Accounts_ID
					FROM AB_Control_Accounts
					WHERE Control_Number = 106    --Cost Of Sales Control

				--> Create JOURNAL DETAIL for Cost Of Sales Control
					EXEC sp_AB_Insert_Journal_Detail
							@JNLHeaderID,
							@GLControlAccount,
							@SumTotalCost,
							@Narration,
							@UserID,
							@CompanyID,
							@InsertGLTran
    
				--> Create GL TRANSACTION for Cost Of Sales Control
					EXEC sp_AB_Insert_GL_Transactions
							@Narration,
							22,
							@GLControlAccount,
							@DayEndDate,
							'106 Cost of Sales',
							@Month,
							@Year,
							@NextGLTranID,
							@SumTotalCost,
							@UserID,
							@CompanyID

				--> Reverse signs to balance double entry
					SET @SumTotalCost = @SumTotalCost * -1
    
				--> Update INVENTORY CONTROL
					SELECT @GLControlAccount = AB_Accounts_ID
					FROM AB_Control_Accounts
					WHERE Control_Number = 601    --Inventory Control

				--> Create JOURNAL DETAIL for Inventory Control
					EXEC sp_AB_Insert_Journal_Detail
							@JNLHeaderID,
							@GLControlAccount,
							@SumTotalCost,
							@Narration,
							@UserID,
							@CompanyID,
							@InsertGLTran
    
				--> Create GL TRANSACTION for Inventory Control
					EXEC sp_AB_Insert_GL_Transactions                                        
							@Narration,
							22,
							@GLControlAccount,
							@DayEndDate,
							'601 Inventory',
							@Month,
							@Year,
							@NextGLTranID,
							@SumTotalCost,
							@UserID,
							@CompanyID

				END    --IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
					
--####################################################################################						
					IF @Levy_Count > 0 --If NO LEVY SALES transactions exist
					BEGIN
						DECLARE Get_Data CURSOR
						FOR
						SELECT 
							p.AP_Products_ID,
				--			p.Description,
				--			p.Product_Code,
							p.GL_Purchases_ID,
							p.GL_Sales_ID,
							p.GL_COS_ID,
							ISNULL(SUM(d.Tax_Amount), 0),
							ISNULL(SUM(d.Extended_Amount), 0),
							Cast( SUM( ISNULL(d.Unit_Cost,0) * ISNULL(d.Quantity,0) ) As Money)
						FROM AS_Transactions t
						Inner Join AS_Transaction_Details d On
							t.AS_Transactions_ID = d.AS_Transactions_ID
						Inner Join AP_Products p On
			  				d.AP_Products_ID = p.AP_Products_ID
						WHERE t.AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
							 (t.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
							  t.Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
							  t.Day_End IS NULL AND
							  t.Transaction_Date <= @CutOffDate AND
							  p.Slu_AW_YesNo_Levy_Item = 1                              
						GROUP BY 
							p.AP_Products_ID, 			
							p.GL_Purchases_ID,
							p.GL_Sales_ID,
							p.GL_COS_ID

                        OPEN Get_Data
						FETCH NEXT FROM Get_Data 
        				INTO
        					@Levy_AP_Products_ID,
        					@Levy_GRInventoryCOS_ID,
							@Levy_PostGLSales_ID,
							@Levy_PostGLCOS_ID,
							@Levy_SumTax,
							@Levy_SumTotalAmount,
							@Levy_SumTotalCost    
                    	
        				WHILE (@@FETCH_STATUS = 0)
        				BEGIN                        
                            Set @SumTax = ROUND(@Levy_SumTax, 2)
                            Set @SumTotalAmount = ROUND(@Levy_SumTotalAmount, 2)
							Set @SumTotalCost = ROUND(@Levy_SumTotalCost, 2)
						   
							SET @Narration = 'Day End - Sales Levy'

						--> Create NORMAL JOURNAL header for the Sales Journal
							IF @NextGLTranID = 0
							BEGIN

         						EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
										22,
										@CompanyID
	            
        						EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
										@DayEndDate,
										@NextGLTranID,
										@Narration,
										@Month,
										@Year,
										@UserID,
										@CompanyID

							END

						--> Update DEBTORS CONTROL
    						SELECT @GLControlAccount = AB_Accounts_ID
							FROM AB_Control_Accounts
							WHERE Control_Number = 101    --Debtors Control

						--> Create JOURNAL DETAIL for Debtors Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@Levy_SumTotalAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran

						--> Create GL TRANSACTION for Debtors Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'101 Debtors Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@Levy_SumTotalAmount,
									@UserID,
									@CompanyID

						--> Reverse signs to balance double entry
    						SET @SalesAmount = (@Levy_SumTotalAmount - @Levy_SumTax) * -1
							SET @TaxAmount = @Levy_SumTax * -1
	    
						--> Update SALES CONTROL
							--SELECT @GLControlAccount = AB_Accounts_ID
							--FROM AB_Control_Accounts
							--WHERE Control_Number = 102    --Sales Control
						--> Use product GL account	
                            Set @GLControlAccount = @Levy_PostGLSales_ID  

						--> Create JOURNAL DETAIL for Sales Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@SalesAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran
	    
						--> Create GL TRANSACTION for Sales Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'102 Sales Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@SalesAmount,
									@UserID,
									@CompanyID

						--> UPDATE GL - VAT Control
							SELECT @GLControlAccount = AB_Accounts_ID
							FROM AB_Control_Accounts
							WHERE Control_Number = 401    --VAT Control

							SET @Narration = 'Day End - VAT on Sales Levy'

						--> Create JOURNAL DETAIL for VAT Control
							EXEC sp_AB_Insert_Journal_Detail
									@JNLHeaderID,
									@GLControlAccount,
									@TaxAmount,
									@Narration,
									@UserID,
									@CompanyID,
									@InsertGLTran

						--> Create GL TRANSACTION for VAT Control
							EXEC sp_AB_Insert_GL_Transactions
									@Narration,
									22,
									@GLControlAccount,
									@DayEndDate,
									'401 VAT on Sales Levy',
									@Month,
									@Year,
									@NextGLTranID,
									@TaxAmount,
									@UserID,
									@CompanyID

							SET @Count = 0

			--> COST OF SALES -----------------------------------------------------

						--> Get parameter 'Post GL COST-OF-SALES in Day-End to each Product's Cost-of-Sales GL Account'
							SELECT @PostGLCOS = RTRIM(LTRIM(Control_Value))
							FROM Sys_AW_Options
							WHERE Control_Type = 'CheckBox' AND
								  Control_Name = 'chkUseProductCOSGL' AND
								  Control_Index = 0 AND
								  AW_User_Companies_ID = @CompanyID


						--> Get parameter 'Post directly to Inventory and Cost-of-Sales accounts  (Continous Inventory method)
							SELECT @GRInventoryCOS = RTRIM(LTRIM(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

	--------------------------------------------------------------------------------------------
	-- ToDo: ADD NEW CURSOR GROUP BY AP_Products.GL_COS_ID  (Cost-of-Sales GL Account)
	--------------------------------------------------------------------------------------------

								SET @Narration = 'Day End - Cost Of Sales Levy'
	            
							--> Create NORMAL JOURNAL header for Cost Of Sales
								IF @NextGLTranID = 0
								BEGIN

             						EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
											22,
											@CompanyID
	                
            						EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
											@DayEndDate,
											@NextGLTranID,
											@Narration,
											@Month,
											@Year,
											@UserID,
											@CompanyID

								END
	            
							--> Update COST OF SALES CONTROL
        						--SELECT @GLControlAccount = AB_Accounts_ID
								--FROM AB_Control_Accounts
								--WHERE Control_Number = 106    --Cost Of Sales Control
							--> Use product GL account	
                            Set @GLControlAccount = @Levy_PostGLCOS_ID  

							--> Create JOURNAL DETAIL for Cost Of Sales Control
								EXEC sp_AB_Insert_Journal_Detail
										@JNLHeaderID,
										@GLControlAccount,
										@SumTotalCost,
										@Narration,
										@UserID,
										@CompanyID,
										@InsertGLTran
	            
							--> Create GL TRANSACTION for Cost Of Sales Control
								EXEC sp_AB_Insert_GL_Transactions
										@Narration,
										22,
										@GLControlAccount,
										@DayEndDate,
										'106 Cost of Sales Levy',
										@Month,
										@Year,
										@NextGLTranID,
										@SumTotalCost,
										@UserID,
										@CompanyID

							--> Reverse signs to balance double entry
								SET @SumTotalCost = @SumTotalCost * -1
	            
							--> Update INVENTORY CONTROL
								--SELECT @GLControlAccount = AB_Accounts_ID
								--FROM AB_Control_Accounts
								--WHERE Control_Number = 601    --Inventory Control
							--> Use product GL account	
                            Set @GLControlAccount = @Levy_GRInventoryCOS_ID  

							--> Create JOURNAL DETAIL for Inventory Control
								EXEC sp_AB_Insert_Journal_Detail
										@JNLHeaderID,
										@GLControlAccount,
										@SumTotalCost,
										@Narration,
										@UserID,
										@CompanyID,
										@InsertGLTran
	            
							--> Create GL TRANSACTION for Inventory Control
								EXEC sp_AB_Insert_GL_Transactions                                        
										@Narration,
										22,
										@GLControlAccount,
										@DayEndDate,
										'601 Inventory Levy',
										@Month,
										@Year,
										@NextGLTranID,
										@SumTotalCost,
										@UserID,
										@CompanyID

	    
							END    --IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
						FETCH NEXT FROM Get_Data 
        				INTO
        					@Levy_AP_Products_ID,
        					@Levy_GRInventoryCOS_ID,
							@Levy_PostGLSales_ID,
							@Levy_PostGLCOS_ID,
							@Levy_SumTax,
							@Levy_SumTotalAmount,
							@Levy_SumTotalCost    
												
        				END    	
    					CLOSE Get_Data
    					DEALLOCATE Get_Data
						
					END	--If LEVY SALES transactions exist		
--####################################################################################						
																			
                END    --IF @Count > 0    --If SALES transactions exist


    --> RECEIPTS-----------------------------------------------------------

            SET @SumTotalAmount = 0
            SET @Count = 0

            SET @POSReceipts = 0
            SET @BOFReceipts = 0
            SET @EFTReceipts = 0
            SET @POSCount = 0
            SET @BOFCount = 0
            SET @EFTCount = 0

        --> Get POS RECEIPTS (for the CASH CONTROL)
			SELECT @POSReceipts = ISNULL(SUM(Total_Amount), 0),
                   @POSCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 7          --POS Receipts
              AND Transaction_Date <= @CutOffDate

            SET @POSReceipts = ROUND(@POSReceipts, 2)


        --> Get BOF RECEIPTS (for the CASH CONTROL)
			SELECT @BOFReceipts = ISNULL(SUM(Total_Amount), 0),
                   @BOFCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 21         --BACK OFFICE Receipts
              AND Transaction_Date <= @CutOffDate

            SET @BOFReceipts = ROUND(@BOFReceipts, 2)


        --> Get EFT RECEIPTS (for the CASH CONTROL)
			SELECT @EFTReceipts = ISNULL(SUM(Total_Amount), 0),
                   @EFTCount = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 22         --EFT Receipts
              AND Transaction_Date <= @CutOffDate

            SET @EFTReceipts = ROUND(@EFTReceipts, 2)


            SET @SumTotalAmount = @POSReceipts + @BOFReceipts + @EFTReceipts
            SET @Count = @POSCount + @BOFCount + @EFTCount


            IF @Count > 0
            --> Update DEBTORS CONTROL ------------------------------
                BEGIN

                    SET @Narration = 'Day End - Receipts'

                --> Create NORMAL JOURNAL header for the Sales Journal
                    IF @NextGLTranID = 0
                        BEGIN

             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    22,
                                    @CompanyID
            
            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @DayEndDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID

                        END

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 101    --DEBTORS CONTROL

                --> Create JOURNAL DETAIL for Debtors Control
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @SumTotalAmount,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION for DEBTORS CONTROL
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            22,
                            @GLControlAccount,
                            @DayEndDate,
                            '101 Total Receipts',
                            @Month,
                            @Year,                                @NextGLTranID,
                            @SumTotalAmount,
                            @UserID,
                            @CompanyID


                    IF @POSCount > 0
                    --> Update CASH CONTROL ---------------------------------
                        BEGIN
                            SELECT @GLControlAccount = AB_Accounts_ID
                            FROM AB_Control_Accounts
                            WHERE Control_Number = 206    --CASH CONTROL
    
                            SET @POSReceipts = -(@POSReceipts)

                            SET @Narration = 'Day End - POS Receipts'

                        --> Create JOURNAL DETAIL for CASH CONTROL
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @POSReceipts,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran
    
                        --> Create GL TRANSACTION for Cash Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLControlAccount,
                                    @DayEndDate,
                                    '206 POS Receipts',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,                                        @POSReceipts,
                                    @UserID,
                                    @CompanyID

                        END

                    SET @Count = @BOFCount + @EFTCount
                    SET @SumTotalAmount = 0

                    IF @Count > 0
                    --> Update TRADE DEBTORS PAYMENT CLEARING ---------------
                        BEGIN
                            SELECT @GLControlAccount = AB_Accounts_ID
                            FROM AB_Control_Accounts
                            WHERE Control_Number = 105    --TRADE DEBTORS PAYMENT CLEARING

                            SET @SumTotalAmount = @BOFReceipts + @EFTReceipts
                            SET @SumTotalAmount = -(@SumTotalAmount)

                            SET @Narration = 'Day End - OTHER Receipts'

                        --> Create JOURNAL DETAIL for DEBTORS PAYMENT CLEARING
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLControlAccount,
                                    @SumTotalAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran
    
                        --> Create GL TRANSACTION for DEBTORS PAYMENT CLEARING
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLControlAccount,
                                    @DayEndDate,
                                    '105 Other Receipts',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @SumTotalAmount,
                                    @UserID,
                                    @CompanyID

                        END

                END


    --> INTEREST - IS UPDATED IN CUSTOMERS INTEREST JOURNALS --------------


    --> SETTLEMENT DISCOUNT------------------------------------------------

            SET @SumTotalAmount = 0
            SET @Count = 0

        --> Get SETTLEMENT DISCOUNT total - NB: THIS IS A NEGATIVE NUMBER
			SELECT @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                   @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions 
            WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                  Day_End IS NULL AND
                  Sys_AW_Transaction_Types_ID = 18         --Settlement Disc
              AND Transaction_Date <= @CutOffDate

            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


            IF @Count > 0
            --> Update DEBTORS CONTROL
                BEGIN

                --> (NEW 06 JUL 2002) VAT ON SETTLEMENT DISCOUNT --------
                    --Get the Current Tax Rate
                    SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                    FROM Sys_AW_Tax_Codes
                    WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                    
                    SET @Settlement_VAT = ROUND((@SumTotalAmount * (@TaxRate / (100 + @TaxRate))) ,2)
                    SET @Settlement_Ex_VAT = (@SumTotalAmount - @Settlement_VAT) 
                    
                    --Make both amounts Debits
                    SET @Settlement_VAT = (@Settlement_VAT * -1)
                    SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                    
                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 103    --SETTLEMENT DISCOUNT ALLOWED

                --> Create NORMAL JOURNAL header for the Sales Journal
                    IF @NextGLTranID = 0
                        BEGIN

             				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                    24,
                                    @CompanyID
            
            				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                    @DayEndDate,
                                    @NextGLTranID,
                                    @Narration,
                                    @Month,
                                    @Year,
                                    @UserID,
                                    @CompanyID

                        END

                    SET @Narration = 'Day End - Settlement Disc Ex VAT'

                --> Create JOURNAL DETAIL for Settlement Discount Allowed
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @Settlement_Ex_VAT,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran
                
                --> Create GL TRANSACTION: DEBIT Settlement Discount Allowed
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '103 Settlement Disc',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Settlement_Ex_VAT,
                            @UserID,
                            @CompanyID

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 401    --VAT Control

                    SET @Narration = 'Day End - Settlement Disc VAT'

                --> Create JOURNAL DETAIL for VAT on Settlement Discount
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @Settlement_VAT,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran
                
                --> Create GL TRANSACTION: DEBIT VAT Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '401 Settlement VAT',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @Settlement_VAT,
                            @UserID,
                            @CompanyID

                --> (END NEW 06 JUL 2002) VAT ON SETTLEMENT DISCOUNT ----

                    SET @Narration = 'Day End - Settlement Discount'

                    SELECT @GLControlAccount = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 101    --Debtors Control

                --> Create JOURNAL DETAIL for Debtors Control (a Credit)
                    EXEC sp_AB_Insert_Journal_Detail
                            @JNLHeaderID,
                            @GLControlAccount,
                            @SumTotalAmount,
                            @Narration,
                            @UserID,
                            @CompanyID,
                            @InsertGLTran

                --> Create GL TRANSACTION: CREDIT Debtors Control
                    EXEC sp_AB_Insert_GL_Transactions
                            @Narration,
                            24,
                            @GLControlAccount,
                            @DayEndDate,
                            '101 Settlement Disc',
                            @Month,
                            @Year,
                            @NextGLTranID,
                            @SumTotalAmount,
                            @UserID,
                            @CompanyID

                    SET @Count = 0

                END

 --   --> Consignment------------------------------------------------

	--		SELECT @SumConsignmentTax = ISNULL(SUM(Total_Tax_Amount), 0),
 --                  @SumConsignmentTotalAmount = ISNULL(SUM(Total_Amount), 0),
 --                  @SumConsignmentTotalCost = ISNULL(SUM(Total_Cost), 0),
 --                  @Count = ISNULL(COUNT(*), 0)
	--		FROM AS_Transactions
 --           WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
 --                (Sys_AW_Transaction_Types_ID = 33  OR      -- Consignment Note
 --                 Sys_AW_Transaction_Types_ID = 34  OR      -- Consignment Sold
 --                 Sys_AW_Transaction_Types_ID = 35) AND     -- Consignment Returned
 --                 Day_End IS NULL
 --             AND Transaction_Date <= @CutOffDate

 --           SET @SumConsignmentTax = ROUND(@SumConsignmentTax, 2)
 --           SET @SumConsignmentTotalAmount = ROUND(@SumConsignmentTotalAmount, 2)
 --           SET @SumConsignmentTotalCost = ROUND(@SumConsignmentTotalCost, 2)        
        
	--		--> Reverse signs to balance double entry
	--		SET @SumConsignmentTotalCost = @SumConsignmentTotalCost * -1
	--		SET @SumConsignmentTax = @SumConsignmentTax * -1

 --           IF @Count > 0
 --           --> Update DEBTORS CONTROL
 --           BEGIN

	--			--Consignment Debtor
	--			SET @Narration = 'Day End - Consignment Sales'
	--			SET @GLControlAccount = 0
				
	--			--Consignment Trade Debtors
	--			SELECT @GLControlAccount = AB_Accounts_ID
	--			FROM AB_Control_Accounts
	--			WHERE Control_Number = 703

 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID
    
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTotalAmount,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran

	--		--> Create GL TRANSACTION for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'703 Consignment Debtors',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTotalAmount,
	--					@UserID,
	--					@CompanyID

	--			SET @Narration = 'Day End - Consignment Inentory'
	--			SET @GLControlAccount = 0
    		    
 --   		    -- Consignment Inventory
 --   			SELECT @GLControlAccount = AB_Accounts_ID
 --               FROM AB_Control_Accounts
 --               WHERE Control_Number = 701                
    		
 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID    	
							
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Trade Debtors
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTotalCost,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran
    		
	--			--> INSERT Consignment Inventory GL entry
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'701 Consignment Inentory',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTotalCost,
	--					@UserID,
	--					@CompanyID

	--			SET @Narration = 'Day End - Consignment VAT'
	--			SET @GLControlAccount = 0

 --   		    -- Consignment VAT
 --   			SELECT @GLControlAccount = AB_Accounts_ID
 --               FROM AB_Control_Accounts
 --               WHERE Control_Number = 704                
    		
 --				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
	--					22,
	--					@CompanyID    	
							
	--			EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
	--					@DayEndDate,
	--					@NextGLTranID,
	--					@Narration,
	--					@Month,
	--					@Year,
	--					@UserID,
	--					@CompanyID				

	--		--> Create JOURNAL DETAIL for Consignment Inventory
	--			EXEC sp_AB_Insert_Journal_Detail
	--					@JNLHeaderID,
	--					@GLControlAccount,
	--					@SumConsignmentTax,
	--					@Narration,
	--					@UserID,
	--					@CompanyID,
	--					@InsertGLTran
    		
	--			--> INSERT Consignment VAT GL entry
	--			EXEC sp_AB_Insert_GL_Transactions
	--					@Narration,
	--					22,
	--					@GLControlAccount,
	--					@DayEndDate,
	--					'704 Consignment VAT',
	--					@Month,
	--					@Year,
	--					@NextGLTranID,
	--					@SumConsignmentTax,
	--					@UserID,
	--					@CompanyID

	--		END -- Consignment
			
	----> Consignment------------------------------------------------

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG
-------------------------------------------------------------------------
			UPDATE AS_Transactions
            SET Day_End = @DayEndDate
            WHERE Day_End IS NULL AND
                  AW_User_Companies_ID = @CompanyID
              AND Transaction_Date <= @CutOffDate

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG in AS_Till_Payouts
-------------------------------------------------------------------------
			UPDATE AS_Till_Payouts
            SET Day_End = @DayEndDate
            WHERE Day_End IS NULL AND
                  AW_User_Companies_ID = @CompanyID
              AND Payout_Date <= @CutOffDate

-------------------------------------------------------------------------
--> INSERT INTO AS_Day_Ends TABLE
-------------------------------------------------------------------------
            INSERT AS_Day_Ends
                (
                    Day_End,
                	AB_Transaction_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    AB_Transaction_Ref,
                    Date_Captured,
                    User_ID,
                    AW_User_Companies_ID
                )
            VALUES
                (
                    @DayEndDate,
                    --@CutOffDate, --@DayEndDate, V6.2 @DayEndDate changed to ShortDateTime Check!!!!!!!!!!!!!!!!
                    @DayEndDate,
                    @Month,
                    @Year,
                    @NextGLTranID,
                    @DayEndDate,
                    @UserID,
                    @CompanyID
                )
-------------------------------------------------------------------------
			--Populates Day End summary tables

			EXEC sp_AS_Day_End_Summary @DayEndDate, @CompanyID

		COMMIT TRANSACTION

        SET @RetVal = 1
	END

    ELSE
	IF @Choice = 2    --Reverse a Day-End
		BEGIN
			BEGIN TRANSACTION
			
    			UPDATE AS_Transactions
                SET Day_End = NULL
                WHERE AW_User_Companies_ID = @CompanyID
                  --AND Day_End = @DayEndDate
					AND Day_End = @CutOffDate                  

    			--UPDATE AS_Day_Ends
       --         SET Slu_AW_Active_ID = 5
       --         WHERE AW_User_Companies_ID = @CompanyID
       --           AND Day_End = @DayEndDate

			COMMIT TRANSACTION
		END

    ELSE
	IF @Choice = 3    --(Not Used)
		BEGIN
			SELECT *
            FROM vw_RPT_AS_Transactions_Transaction_Details
            WHERE DATEDIFF(d, @DayEndDate, tDayEnd) = 0 AND
                  tCompanyID = @CompanyID
		END

    ELSE
	IF @Choice = 4 -- Check if any Day-Ends have been done this minute/day
		BEGIN
			SELECT TOP 1 @DayEndCheck = Day_End
            FROM AS_Transactions
            WHERE DATEDIFF(n, @DayEndDate, Day_End) = 0 AND           --n = minute
                  AW_User_Companies_ID = @CompanyID                   --Added 04/06/05
			
            IF @DayEndCheck IS NULL 
				BEGIN 
					SELECT TOP 1 @DayEndCheck = Day_End
                    FROM AS_Transactions
                    WHERE DATEDIFF(d, @DayEndDate, Day_End) = 0 AND   --d = day
                          AW_User_Companies_ID = @CompanyID           --Added 04/06/05
					
                    IF NOT @DayEndCheck IS NULL 
						SET @RetVal = 1    -- A Day-End was done during this day
				END
			ELSE
				SET @RetVal = 2            -- A Day-End was done during this minute
		END

RETURN @RetVal
SET NOCOUNT OFF
GO
IF NOT EXISTS
(
	SELECT * 
	FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[AS_Transaction_Details_Consignment]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
BEGIN

	CREATE TABLE AS_Transaction_Details_Consignment
	(
		[AS_Transaction_Details_Consignment_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transaction_Details_ID] int NOT NULL, --Sys_AW_Transaction_Types_ID 33 Consignment Stock Note
		[Consignment_ID] int NULL,
		[Sys_AW_Transaction_Types_ID] Int NULL,
		[Quantity] Decimal(9, 3) NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		CONSTRAINT [PK_AS_Transaction_Details_Consignment] PRIMARY KEY CLUSTERED 
		(
			[AS_Transaction_Details_Consignment_ID] ASC
		)
	)
	
END
GO
	
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_Zero]', @objname = N'[dbo].[AS_Transaction_Details_Consignment].[Quantity]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_Companies]', @objname = N'[dbo].[AS_Transaction_Details_Consignment].[AW_User_Companies_ID]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_Date_Captured]', @objname = N'[dbo].[AS_Transaction_Details_Consignment].[Date_Captured]'
	GO
	EXECUTE sp_bindefault @defname = N'[dbo].[df_User_ID]', @objname = N'[dbo].[AS_Transaction_Details_Consignment].[User_ID]'
	GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transaction_Details_Consignment_AS_Transaction_Details_ID'
)
DROP INDEX AS_Transaction_Details_Consignment.IX_AS_Transaction_Details_Consignment_AS_Transaction_Details_ID
GO
CREATE INDEX IX_AS_Transaction_Details_Consignment_AS_Transaction_Details_ID
   ON AS_Transaction_Details_Consignment (AS_Transaction_Details_ID)
	WITH FILLFACTOR = 80
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Day_End_Sales_Split_Types]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Day_End_Sales_Split_Types]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Day_End_Sales_Split_Types
--Purpose       :Day-End procedure with Sales SPLIT by PRODUCT TYPE
--              :Inserts GL Journal and GL Transactions to GL CONTROL ACCOUNTS:
--              :1. DEBTORS, SALES, & VAT CONTROL
--              :2. RECEIPTS to DEBTORS & CASH CONTROL
--              :3. INTEREST JOURNALS to DEBTORS & INTEREST RECEIVED - Removed 31/05/04
--              :4. SETTLEMENT DISCOUNT to DEBTORS & SETTLEMENT DISCOUNT ALLOWED
--              :    for the following AS_Transaction_Types:
--              :        3=Invoice, 4=Refund, 7=Receipt,
--              :        15=Interest Journal, 18=Settlement Discount
--              :
--              :Ignores 5=Customer Journals. This is updated in Customer Journals
--              :-------------------------------------------------------
--              :GL Transaction Ref no's: !! REDUNDANT 15/10/03 !!
--              :Sales:            Debtors = 90, Sales = 91, VAT = 92
--              :Cost Of Sales:    Cost Of Sales = 82, Inventory = 83
--              :Receipts:         Debtors = 93, Cash = 94
--              :Interest:         Debtors = 95, Interest Received = 96 - Removed 31/05/04
--              :Settlement:       Debtors = 97, Discount Allowed = 98
--              :-------------------------------------------------------
--Calls         :sp_AB_Next_Transaction_Number
--              :sp_AB_Insert_Journal_Header
--              :sp_AB_Insert_Journal_Detail
--              :sp_AB_Insert_GL_Transactions
--              :sp_AB_Insert_System_GL_Account
--Date          :2006/10/03
--Authors       :TB
--MODS          :
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.3      :12/02/09 - Added new split COST-OF-SALES and INVENTORY by TYPE - RM
--2004.4.6      :08/08/09 - Added UPDATE DAY-END FLAG in NEW AS_Till_Payouts table
--2004.5.3      :09/08/11 - Added Day-End CUTOFF DATE using Transaction_Date and DELETE DAY-END
--              :23/08/11 - Modified @Choice = 5 (Check if Sales Split product totals balance to Sales totals)
--              :           to SET @RetVal = Difference, and removed ZERO splits total return value setting
--2004.5.5      :31/10/11 - Changed Day_End = @CutOffDate to Transaction_Date <= @CutOffDate in @Choice = 5 !!!
--              :           Previously this would have found NO TRANSACTIONS because Day_End WOULD HAVE BEEN NULL !!!
--              :31/10/11 - Fixed SELECT CLAUSE of Sales_Cursor and added Transaction_Date <= @CutOffDate
--              :           to SELECT DAILY SALES TOTALS by TYPE. When a Day End is deleted we only want
--              :           to fetch ALL Day_End IS NULL transactions UP TO THE CUTOFF DATE
--              :10/11/11 - Added Set @RetVal = 1 in DO DAY-END when Day-End completed succesfully
--2004.5.6      :06/12/11 - Changed DECLARE @RetValValue money to @RetValValue float to prevent ROUNDING the result
--              :           and set it to 23061949 if transaction count = 0 (because it ONLY returns INTEGERS)
--2004.6.2 RL   :2015-08-07 - Added Call to sp_AS_Day_End_Summary. Writes to Day End Summary tables
--2004.6.2 RL   :2015-08-07 - Changed @DayEndDate from DateTime to SmallDateTime
--2016.6.2 RL	:2016-08-04	Changed Settlement discount from 22 to 24 ABTranType - AP Settlement
--							So that it shows in its own section on TAX report
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Day_End_Sales_Split_Types]
	(
		@Choice int,
		@CompanyID int,
		@Month tinyint,
		@Year int,
        @UserID int,
        @CutOffDate datetime
	)
AS

SET NOCOUNT ON

	DECLARE @DayEndDate SmallDateTime, --DateTime,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @DayEndCheck DateTime,
            @RetVal int,
            @RetValValue float,
            @SumAmount money,
            @SumTax money,
            @SumTotalAmount money,
            @SumTotalCost money,
            @GLControlAccount int,
            @CostAmount money,
            @SalesAmount money,
            @TaxAmount money,
            @Count int,
            @PAYCount int,
            @POSCount int,
            @BOFCount int,
            @EFTCount int,
            @InsertGLTran bit,
            @Settlement_Disc_Allowed_GL_ID int,
            @Settlement_Ex_VAT money,
            @Settlement_VAT money,
            @POSReceipts money,
            @BOFReceipts money,
            @EFTReceipts money,
            @TaxRate decimal(5,2),
            @SplitGLAccount varchar(50),
            @COSGLDescription varchar(50),
            @SalesGLDescription varchar(50),
            @InventoryGLDescription varchar(50),
            @SplitSales money,
            @GLSalesID int,
            @GLCOSID int,
            @GLInventoryID int


	SET @DayEndDate = @CutOffDate    -- NEW 2004.5.3
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details
    SET @Count = 0
	SET @RetVal = 0


	IF @Choice = 0    --Select list of PREVIOUS DAY-ENDS (PICKLIST)
		BEGIN
			SELECT AS_Day_Ends_ID AS [ID],
                   Day_End,
                   AB_Transaction_Ref AS [GL Tran Ref],
                   AB_Transaction_Date AS [GLTranDate]
            FROM AS_Day_Ends
            WHERE AW_User_Companies_ID = @companyID
            ORDER BY Day_End DESC
		END

	ELSE
	IF @Choice = 1    --Do a NEW DAY-END
		BEGIN
            SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

			BEGIN TRANSACTION

        --> SALES--------------------------------------------------------------

                SET @SumTax = 0
                SET @SumTotalAmount = 0
                SET @SumTotalCost = 0
                SET @Count = 0

            --> Get SALES
				SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                       @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                       @SumTotalCost = ISNULL(SUM(Total_Cost), 0),
                       @Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions
                WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                     (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                      Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                      Day_End IS NULL AND
                      Transaction_Date <= @CutOffDate


                SET @SumTax = ROUND(@SumTax, 2)
                SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)
                SET @SumTotalCost = ROUND(@SumTotalCost, 2)


                ---------------------------------------------------------------------
                --> If SALES transactions exist
                ---------------------------------------------------------------------
                IF @Count > 0
                    BEGIN

                        SET @Narration = 'Day End - Debtors Sales'

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        22,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                    --> Update DEBTORS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --Debtors Control
    
                    --> Create JOURNAL DETAIL for Debtors Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for Debtors Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Debtors Sales',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID


                        SET @Narration = 'Day End - Sales'

                        ---------------------------------------------------------------------
                        --> Post Product Sales in Day-End to a Sales GL Account by Product Type
                        ---------------------------------------------------------------------
                        DECLARE Sales_Cursor CURSOR FOR
                            (
                                SELECT t.[Description],
                                       SUM(d.Extended_Amount - d.Tax_Amount),
                                       SUM(d.Unit_Cost * d.Quantity)
                                FROM AS_Transaction_Details d
                                    INNER JOIN AS_Transactions h
                                        ON h.AS_Transactions_ID = d.AS_Transactions_ID
                                    INNER JOIN AP_Products p
                                        ON d.AP_Products_ID = p.AP_Products_ID
                                    LEFT JOIN Lup_AP_Product_Types t
                                        ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
                                WHERE d.AW_User_Companies_ID = @CompanyID AND
                                     (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                                      h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                                      h.Day_End IS NULL AND
                                      Transaction_Date <= @CutOffDate
                                GROUP BY t.[Description]
                            )

                    	OPEN Sales_Cursor

                    	FETCH NEXT FROM Sales_Cursor 
                    	INTO
                            @SplitGLAccount,
                            @SalesAmount,
                            @CostAmount

                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN

                            SET @SalesAmount = ROUND(@SalesAmount, 2)
                            SET @CostAmount = ROUND(@CostAmount, 2)
                            SET @GLSalesID = 0

                            SET @SalesGLDescription = LEFT('SALES - ' + @SplitGLAccount, 50)
                            SET @COSGLDescription = LEFT('C.O.S. - ' + @SplitGLAccount, 50)
                            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @SplitGLAccount, 50)


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL SALES AccountID
                            ---------------------------------------------------------------------
                            SET @GLSalesID = 0

                            SELECT TOP 1 @GLSalesID = AB_Accounts_ID
                            FROM AB_Accounts
                            WHERE AW_User_Companies_ID = @CompanyID AND
                                 [Description] = @SalesGLDescription AND
                                  Sys_AB_Account_Categories_ID = 13 AND        --REVENUE
                                  Slu_AW_Active_ID = 1

                            IF @GLSalesID = 0
                                BEGIN
                     				EXEC @GLSalesID = sp_AB_Insert_System_GL_Account
                                                            @SalesGLDescription,
                                                            13,
                                                            @UserID,
                                                            @CompanyID
                                END


                            --> Reverse signs SALES amount to balance double entry
            	            SET @SalesAmount = (@SalesAmount * -1)


                            --> Create JOURNAL DETAIL for Sales Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLSalesID,
                                    @SalesAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT SALES Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLSalesID,
                                    @DayEndDate,
                                    '102 Sales',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @SalesAmount,
                                    @UserID,
                                    @CompanyID


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL C.O.S. AccountID
                            ---------------------------------------------------------------------
                            SET @GLCOSID = 0

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

                            IF @GLCOSID = 0
                                BEGIN
                     				EXEC @GLCOSID = sp_AB_Insert_System_GL_Account
                                                            @COSGLDescription,
                                                            14,
                                                            @UserID,
                                                            @CompanyID
                                END

                            --> Create JOURNAL DETAIL for C.O.S. Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLCOSID,
                                    @CostAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT C.O.S. Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLCOSID,
                                    @DayEndDate,
                                    '106 Cost of Sales',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @CostAmount,
                                    @UserID,
                                    @CompanyID


                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID
                            ---------------------------------------------------------------------
                            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        --INVENTORIES
                                  Slu_AW_Active_ID = 1

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


                            --> Reverse signs INVENTORY amount to balance double entry
            	            SET @CostAmount = (@CostAmount * -1)


                            --> Create JOURNAL DETAIL for INVENTORY Control
                            EXEC sp_AB_Insert_Journal_Detail
                                    @JNLHeaderID,
                                    @GLInventoryID,
                                    @CostAmount,
                                    @Narration,
                                    @UserID,
                                    @CompanyID,
                                    @InsertGLTran

                            --> Create GL TRANSACTION for SPLIT INVENTORY Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @Narration,
                                    22,
                                    @GLInventoryID,
                                    @DayEndDate,
                                    '601 Inventory',
                                    @Month,
                                    @Year,
                                    @NextGLTranID,
                                    @CostAmount,
                                    @UserID,
                                    @CompanyID


                        	FETCH NEXT FROM Sales_Cursor 
                        	INTO
                                @SplitGLAccount,
                                @SalesAmount,
                                @CostAmount

                    	END

                    	CLOSE Sales_Cursor

                    	DEALLOCATE Sales_Cursor
                        ---------------------------------------------------------------------


                    --> Reverse signs to balance double entry
                        SET @TaxAmount = (@SumTax * -1)


                    --> UPDATE GL - VAT Control
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 401    --VAT Control

                        SET @Narration = 'Day End - VAT on Sales'

                    --> Create JOURNAL DETAIL for VAT Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @TaxAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for VAT Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '401 VAT on Sales',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @TaxAmount,
                                @UserID,
                                @CompanyID
    
--                        SET @Count = 0

                    END    --IF @Count > 0    --If SALES transactions exist


        --> COST OF SALES - IS UPDATED IN STOCK RECEIPTS GRV ------------------


        --> RECEIPTS-----------------------------------------------------------

                SET @SumTotalAmount = 0
                SET @PAYCount = 0
                SET @Count = 0

                SET @POSReceipts = 0
                SET @BOFReceipts = 0
                SET @EFTReceipts = 0
                SET @POSCount = 0
                SET @BOFCount = 0
                SET @EFTCount = 0


            --> Get POS RECEIPTS (for the CASH CONTROL)
				SELECT @POSReceipts = ISNULL(SUM(Total_Amount), 0),
                       @POSCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 7 AND      --POS Receipts
                      Transaction_Date <= @CutOffDate

                SET @POSReceipts = ROUND(@POSReceipts, 2)


            --> Get BOF RECEIPTS (for the CASH CONTROL)
				SELECT @BOFReceipts = ISNULL(SUM(Total_Amount), 0),
                       @BOFCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 21 AND     --BACK OFFICE Receipts
                      Transaction_Date <= @CutOffDate

                SET @BOFReceipts = ROUND(@BOFReceipts, 2)


            --> Get EFT RECEIPTS (for the CASH CONTROL)
				SELECT @EFTReceipts = ISNULL(SUM(Total_Amount), 0),
                       @EFTCount = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 22 and     --EFT Receipts
                      Transaction_Date <= @CutOffDate

                SET @EFTReceipts = ROUND(@EFTReceipts, 2)


                SET @SumTotalAmount = @POSReceipts + @BOFReceipts + @EFTReceipts
                SET @PAYCount = @POSCount + @BOFCount + @EFTCount


                ---------------------------------------------------------------------
                --> If PAYMENT transactions exist
                ---------------------------------------------------------------------
                IF @PAYCount > 0
                    BEGIN

                        ---------------------------------------------------------------------
                        --> Update DEBTORS CONTROL - TOTAL RECEIPTS
                        ---------------------------------------------------------------------
                        SET @Narration = 'Day End - Total Receipts'

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        22,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --DEBTORS CONTROL
    
                    --> Create JOURNAL DETAIL for Debtors Control
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION for DEBTORS CONTROL
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                22,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Total Receipts',
                                @Month,
                                @Year,                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID


                        ---------------------------------------------------------------------
                        --> Update CASH CONTROL - POS RECEIPTS
                        ---------------------------------------------------------------------
                        IF @POSCount > 0
                            BEGIN
                                SELECT @GLControlAccount = AB_Accounts_ID
                                FROM AB_Control_Accounts
                                WHERE Control_Number = 206    --CASH CONTROL
        
                                SET @POSReceipts = (@POSReceipts * -1)

                                SET @Narration = 'Day End - POS Receipts'
        
                            --> Create JOURNAL DETAIL for CASH CONTROL
                                EXEC sp_AB_Insert_Journal_Detail
                                        @JNLHeaderID,
                                        @GLControlAccount,
                                        @POSReceipts,
                                        @Narration,
                                        @UserID,
                                        @CompanyID,
                                        @InsertGLTran
        
                            --> Create GL TRANSACTION for Cash Control
                                EXEC sp_AB_Insert_GL_Transactions
                                        @Narration,
                                        22,
                                        @GLControlAccount,
                                        @DayEndDate,
                                        '206 POS Receipts',
                                        @Month,
                                        @Year,
                                        @NextGLTranID,                                        @POSReceipts,
                                        @UserID,
                                        @CompanyID
        
                            END

                        SET @Count = @BOFCount + @EFTCount
                        SET @SumTotalAmount = 0

                        ---------------------------------------------------------------------
                        --> Update TRADE DEBTORS PAYMENT CLEARING - OTHER Receipts
                        ---------------------------------------------------------------------
                        IF @Count > 0
                            BEGIN
                                SELECT @GLControlAccount = AB_Accounts_ID
                                FROM AB_Control_Accounts
                                WHERE Control_Number = 105    --TRADE DEBTORS PAYMENT CLEARING

                                SET @SumTotalAmount = @BOFReceipts + @EFTReceipts
                                SET @SumTotalAmount = (@SumTotalAmount * -1)

                                SET @Narration = 'Day End - OTHER Receipts'
        
                            --> Create JOURNAL DETAIL for DEBTORS PAYMENT CLEARING
                                EXEC sp_AB_Insert_Journal_Detail
                                        @JNLHeaderID,
                                        @GLControlAccount,
                                        @SumTotalAmount,
                                        @Narration,
                                        @UserID,
                                        @CompanyID,
                                        @InsertGLTran
        
                            --> Create GL TRANSACTION for DEBTORS PAYMENT CLEARING
                                EXEC sp_AB_Insert_GL_Transactions
                                        @Narration,
                                        22,
                                        @GLControlAccount,
                                        @DayEndDate,
                                        '105 Other Receipts',
                                        @Month,
                                        @Year,
                                        @NextGLTranID,
                                        @SumTotalAmount,
                                        @UserID,
                                        @CompanyID
        
                            END

                    END        --> If PAYMENT transactions exist


        --> INTEREST - IS UPDATED IN CUSTOMERS INTEREST JOURNALS --------------


        --> SETTLEMENT DISCOUNT------------------------------------------------

                SET @SumTotalAmount = 0
                SET @Count = 0

            --> Get SETTLEMENT DISCOUNT total - NB: THIS IS A NEGATIVE NUMBER
				SELECT @SumTotalAmount = ISNULL(SUM(Total_Amount), 0),
                       @Count = ISNULL(COUNT(*), 0)
				FROM AS_Transactions 
                WHERE AW_User_Companies_ID = @companyID AND    --Added 04/06/05
                      Day_End IS NULL AND
                      Sys_AW_Transaction_Types_ID = 18 AND     --Settlement Disc
                      Transaction_Date <= @CutOffDate

                SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


                ---------------------------------------------------------------------
                --> If SETTLEMENT DISCOUNT transactions exist
                ---------------------------------------------------------------------
                IF @Count > 0
                    BEGIN

                    --> VAT ON SETTLEMENT DISCOUNT --------
                        --Get the Current Tax Rate
                        SELECT @TaxRate = ISNULL(Tax_Rate, 0)
                        FROM Sys_AW_Tax_Codes
                        WHERE Tax_Code = 'S'    --Standard (Current) rate (e.g. 14%)
                        
                        SET @Settlement_VAT = ROUND((@SumTotalAmount * (@TaxRate / (100 + @TaxRate))) ,2)
                        SET @Settlement_Ex_VAT = (@SumTotalAmount - @Settlement_VAT) 
                        
                        --Make both amounts Debits
                        SET @Settlement_VAT = (@Settlement_VAT * -1)
                        SET @Settlement_Ex_VAT = (@Settlement_Ex_VAT * -1)
                        
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 103    --SETTLEMENT DISCOUNT ALLOWED

                    --> Create NORMAL JOURNAL header for the Sales Journal
                        IF @NextGLTranID = 0
                            BEGIN
                 				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                        24,
                                        @CompanyID
                
                				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                        @DayEndDate,
                                        @NextGLTranID,
                                        @Narration,
                                        @Month,
                                        @Year,
                                        @UserID,
                                        @CompanyID
                            END

                        SET @Narration = 'Day End - Settlement Disc Ex VAT'
                    
                    --> Create JOURNAL DETAIL for Settlement Discount Allowed
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @Settlement_Ex_VAT,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
                    
                    --> Create GL TRANSACTION: DEBIT Settlement Discount Allowed
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '103 Settlement Disc',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @Settlement_Ex_VAT,
                                @UserID,
                                @CompanyID

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 401    --VAT Control

                        SET @Narration = 'Day End - Settlement Disc VAT'

                    --> Create JOURNAL DETAIL for VAT on Settlement Discount
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @Settlement_VAT,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
                    
                    --> Create GL TRANSACTION: DEBIT VAT Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '401 Settlement VAT',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @Settlement_VAT,
                                @UserID,
                                @CompanyID

                    --> VAT ON SETTLEMENT DISCOUNT

                        SET @Narration = 'Day End - Settlement Discount'

                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 101    --Debtors Control

                    --> Create JOURNAL DETAIL for Debtors Control (a Credit)
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @SumTotalAmount,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran

                    --> Create GL TRANSACTION: CREDIT Debtors Control
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                24,
                                @GLControlAccount,
                                @DayEndDate,
                                '101 Settlement Disc',
                                @Month,
                                @Year,
                                @NextGLTranID,
                                @SumTotalAmount,
                                @UserID,
                                @CompanyID

                        SET @Count = 0

                    END


-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG
-------------------------------------------------------------------------
				UPDATE AS_Transactions
                SET Day_End = @DayEndDate
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End IS NULL AND
                      Transaction_Date <= @CutOffDate

-------------------------------------------------------------------------
--> UPDATE DAY-END FLAG in AS_Till_Payouts
-------------------------------------------------------------------------
				UPDATE AS_Till_Payouts
                SET Day_End = @DayEndDate
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End IS NULL AND
                      Payout_Date <= @CutOffDate

-------------------------------------------------------------------------
--> INSERT INTO AS_Day_Ends TABLE
-------------------------------------------------------------------------
                INSERT AS_Day_Ends
                    (
                        Day_End,
                    	AB_Transaction_Date,
                        Slu_AW_Months_ID,
                        Slu_AW_Years_ID,
                        AB_Transaction_Ref,
                        Date_Captured,
                        User_ID,
                        AW_User_Companies_ID
                    )
                VALUES
                    (
                        @DayEndDate,
                        @DayEndDate,
                        @Month,
                        @Year,
                        @NextGLTranID,
                        @DayEndDate,
                        @UserID,
                        @CompanyID
                    )
-------------------------------------------------------------------------
			--Populates Day End summary tables
			EXEC sp_AS_Day_End_Summary @DayEndDate, @CompanyID

			COMMIT TRANSACTION

            SET @RetVal = 1
		END

    ELSE
	IF @Choice = 2    --Reverse a Day-End
		BEGIN
			BEGIN TRANSACTION
    			UPDATE AS_Transactions
                SET Day_End = NULL
                WHERE AW_User_Companies_ID = @CompanyID AND
                      Day_End = @DayEndDate

    			UPDATE AS_Day_Ends
                SET Slu_AW_Active_ID = 5
                WHERE AW_User_Companies_ID = @CompanyID
                  AND Day_End = @DayEndDate

			COMMIT TRANSACTION
		END

    ELSE
	IF @Choice = 3    --(Not Used)
		BEGIN
			SELECT *
            FROM vw_RPT_AS_Transactions_Transaction_Details
            WHERE DATEDIFF(d, @DayEndDate, tDayEnd) = 0 AND
                  tCompanyID = @CompanyID
		END

    ELSE
	IF @Choice = 4 -- Check if any Day-Ends have been done this minute/day
		BEGIN
			SELECT TOP 1 @DayEndCheck = Day_End
            FROM AS_Transactions
            WHERE DATEDIFF(n, @DayEndDate, Day_End) = 0 AND           --n = minute
                  AW_User_Companies_ID = @CompanyID                   --Added 04/06/05
			
            IF @DayEndCheck IS NULL 
				BEGIN 
					SELECT TOP 1 @DayEndCheck = Day_End
                    FROM AS_Transactions
                    WHERE DATEDIFF(d, @DayEndDate, Day_End) = 0 AND   --d = day
                          AW_User_Companies_ID = @CompanyID           --Added 04/06/05
					
                    IF NOT @DayEndCheck IS NULL 
						SET @RetVal = 1    -- A Day-End was done during this day
				END
			ELSE
				SET @RetVal = 2            -- A Day-End was done during this minute
		END

    ELSE
	IF @Choice = 5     -- Check if Sales Split Day-End totals balance to Sales totals
		BEGIN

            SET @RetVal = 0
            SET @RetValValue = 0
            SET @Count = 0

        --> Get SALES
			SELECT @Count = ISNULL(COUNT(*), 0)
			FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL AND
                  Transaction_Date <= @CutOffDate


            IF @Count = 0
                BEGIN
                    --SET @RetValValue = 0.9999
                    SET @RetValValue = 23061949

                    RETURN @RetValValue
                END


    		SELECT @SumTax = ISNULL(SUM(Total_Tax_Amount), 0),
                   @SumTotalAmount = ISNULL(SUM(Total_Amount), 0)
    		FROM AS_Transactions
            WHERE AW_User_Companies_ID = @companyID AND    -- Added 04/06/05
                 (Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
                  Sys_AW_Transaction_Types_ID = 4) AND     -- Refunds
                  Day_End IS NULL AND
                  Transaction_Date <= @CutOffDate


            SET @SumTax = ROUND(@SumTax, 2)
            SET @SumTotalAmount = ROUND(@SumTotalAmount, 2)


            SELECT @SplitSales = ISNULL(SUM(d.Extended_Amount - d.Tax_Amount), 0)
            FROM AS_Transaction_Details d
                INNER JOIN AS_Transactions h
                    ON h.AS_Transactions_ID = d.AS_Transactions_ID
                INNER JOIN AP_Products p
                    ON d.AP_Products_ID = p.AP_Products_ID
                LEFT JOIN Lup_AP_Product_Types t
                    ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID
            WHERE d.AW_User_Companies_ID = @CompanyID AND
                 (h.Sys_AW_Transaction_Types_ID = 3 OR        -- Invoices
                  h.Sys_AW_Transaction_Types_ID = 4) AND      -- Refunds
                  h.Day_End IS NULL AND
                  h.Transaction_Date <= @CutOffDate

            SET @SplitSales = ROUND(@SplitSales, 2)
            SET @RetValValue = (@SumTotalAmount - @SumTax) - @SplitSales


            RETURN @RetValValue
        END

RETURN @RetVal

SET NOCOUNT OFF
GO
--Alter AS_Transaction_Details Table - Add Consignment_Left
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='Consignment_Left'
) 
ALTER TABLE AS_Transaction_Details ADD Consignment_Left Decimal(9,3)
GO

UPDATE AS_Transaction_Details
SET Consignment_Left = 0
Where ISNULL(Consignment_Left,0) = 0
GO
	            
-------------------------------------------------------
EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Consignment_Left]'
-------------------------------------------------------
GO
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_Get_Consignment_Stock_Sold]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Sold]
GO
-------------------------------------------------------------------------------
--Description   :fn_AP_Get_Consignment_Stock_Sold
--Purpose       :Returns consignment quantity sold for a specific AS_Transaction_Detail_ID
--Parameters    :
--Date          :2015/05/21
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_Get_Consignment_Stock_Sold]
	(
        @AS_Transaction_Detail_ID int
	)

RETURNS decimal(9,3)

AS

	BEGIN
    	DECLARE @Qty decimal(9,3)

            SELECT @Qty = ISNULL(SUM(Quantity), 0)
            FROM AS_Transaction_Details_Consignment
            WHERE AS_Transaction_Details_ID = @AS_Transaction_Detail_ID AND
				  Sys_AW_Transaction_Types_ID = 34

    	RETURN @Qty
    END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Cardex_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Cardex_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Cardex_Print
--Purpose       :Product Cardex print fro ONE Product
--Functionality :    uses UNION ALL
--Date          :2004/10/22
--Authors       :TB
--MODS:         :
--2004.3.4      :08/03/07 - Replaced gh.Supplier_Reference with
--              :           gh.Delivery_Note_Number to show Supplier Invoice Number
--2004.3.9      :13/06/08 - Changed [Supplier/Customer] field in ADJUSTMENTS section
--              :           and inserted [Note] from AP_Inventory_Adjustments table
--2004.4.2      :23/10/08 - Change SALES section from Sales Cost to Selling Price - RM
--              :           and [Cost] to [Total]
--2004.5.1      :02/06/11 - Added h.Sys_AW_Transaction_Types_ID = 29 as 'GRVFAC'
--              :           in GOODS RECEIVED for Casing Tracking Factory GRV's
--              :15/06/11 - Added h.Sys_AW_Transaction_Types_ID = 23 as 'TRF IN/OUT'
--              :           in SALES section CASE statement for [TYPE] field
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 31 as 'CRV' and 
--              :            h.Sys_AW_Transaction_Types_ID = 32 as 'CRN' for consignment stock
--V6.2	RL	:2015-10-27		Added h.Sys_AW_Transaction_Types_ID = 33 as 'CON N' and 
--							h.Sys_AW_Transaction_Types_ID = 34 as 'CON S' and 
--              :           h.Sys_AW_Transaction_Types_ID = 35 as 'CON R' for consignment stock sales
--V6.3	RL	:2016-06-07		Changed fn_AP_BFWD_Inventory_On_Hand to only call once. Speed issue
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_RPT_AP_Cardex_Print]

    (
        @StartDate as datetime,
        @ProductID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql			Varchar(8000)
    DECLARE @BFWD			Decimal(9,3)
    DECLARE @DefaultBin		Varchar(50)    

-- SET @StartDate = '2002/01/01 00:00:01'
-- SET @ProductID = 1

	SELECT @DefaultBin = [Description]
	FROM Lup_AP_Product_Bins
	WHERE Lup_AP_Product_Bins_ID = 1

	IF ISNULL(@DefaultBin,'') = ''
		SET @DefaultBin = '<None>'

-------------------------------------------------------------------------------
-- GOODS RECEIVED
-------------------------------------------------------------------------------

	SELECT @BFWD = dbo.fn_AP_BFWD_Inventory_On_Hand(@ProductID, @StartDate)

    SET @sql = ' SELECT '
    SET @sql = @sql + '     gd.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     gd.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(s.Supplier_Name)) AS [Supplier/Customer], '
    --GRVs always done to and from default bin
    SET @sql = @sql + '''' + @DefaultBin + '''' + ' AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN gh.Sys_AW_Transaction_Types_ID = 19 '
    SET @sql = @sql + '          THEN ''GRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 20 '
    SET @sql = @sql + '          THEN ''RETURN'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 29 '
    SET @sql = @sql + '          THEN ''GRVFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 30 '
    SET @sql = @sql + '          THEN ''GRNFAC'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 31 '
    SET @sql = @sql + '          THEN ''CRV'' '
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 32 '
    SET @sql = @sql + '          THEN ''CRN'' '        
    SET @sql = @sql + '          WHEN gh.Sys_AW_Transaction_Types_ID = 34 '
    SET @sql = @sql + '          THEN ''CON S'' '        
    SET @sql = @sql + '          ELSE ''NOGRV'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     gh.Date_Received AS [Date], '

    SET @sql = @sql + '     ISNULL(gh.Delivery_Note_Number, '''') '
    SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), gh.AO_GRV_ID) + '')'' AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(gd.Qty, 0) AS [Qty], '

    SET @sql = @sql + '     ISNULL(gd.Unit_Price, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ISNULL(gd.Net_Amount, 0) AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AO_GRV_Details gd '
    SET @sql = @sql + '         ON p.AP_Products_ID = gd.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AO_GRV gh '
    SET @sql = @sql + '         ON gd.AO_GRV_ID = gh.AO_GRV_ID '
    SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
    SET @sql = @sql + '         ON gh.AO_Suppliers_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON gh.[User_ID] = u.AW_Users_ID '

    SET @sql = @sql + ' WHERE gd.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND gd.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (gh.Sys_AW_Transaction_Types_ID = 19 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 20 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 29 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 30 ' + ' '
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 31 ' + ' '        
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 32 ' + ' '            
    SET @sql = @sql + '     OR gh.Sys_AW_Transaction_Types_ID = 34) ' + ' '   


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- ADJUSTMENTS
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ISNULL(a.Note, '''') AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN a.Sys_AP_Adjustment_Types_ID = 1 '
    SET @sql = @sql + '          THEN ''ADJUST'' '
    SET @sql = @sql + '          WHEN a.Sys_AP_Adjustment_Types_ID = 6 '
    SET @sql = @sql + '          THEN ''TAKEON'' '
    SET @sql = @sql + '          ELSE ''NOADJ'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     CONVERT(datetime, CONVERT(CHAR(10), a.Date_Captured, 121)) AS [Date], '

    SET @sql = @sql + '     CONVERT(varchar(10), a.AP_Inventory_Adjustments_ID) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '        
    SET @sql = @sql + '     ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ISNULL(a.New_Last_Cost, 0) AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0)) * ISNULL(a.New_Last_Cost, 0), 2) AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Inventory_Adjustments a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE a.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (a.Sys_AP_Adjustment_Types_ID = 1 ' + ' '
    SET @sql = @sql + '     OR a.Sys_AP_Adjustment_Types_ID = 6) ' + ' '
    SET @sql = @sql + '   AND ISNULL(a.New_On_Hand, 0) - ISNULL(a.Previous_On_Hand, 0) <> 0 ' + ' '


    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- SALES
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + '     d.AW_User_Companies_ID AS [CompanyID], '

    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     d.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(c.Surname, '''') + ISNULL('', '' + c.Firstnames, ''''))) AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '    

    SET @sql = @sql + '     CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''SALE'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''REFUND'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) < 0) '
    SET @sql = @sql + '          THEN ''TRF IN'' '
    SET @sql = @sql + '          WHEN (h.Sys_AW_Transaction_Types_ID = 23 AND ISNULL(d.Quantity, 0) >= 0) '
    SET @sql = @sql + '          THEN ''TRF OUT'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 33  '
    SET @sql = @sql + '          THEN ''CON N'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 34  '
    SET @sql = @sql + '          THEN ''CON S'' '
    SET @sql = @sql + '          WHEN h.Sys_AW_Transaction_Types_ID = 35  '    
    SET @sql = @sql + '          THEN ''CON R'' '    
    SET @sql = @sql + '          ELSE ''NOSALE'' '
    SET @sql = @sql + '     END AS [Type], '

    SET @sql = @sql + '     h.Transaction_Date AS [Date], '
    SET @sql = @sql + '     h.Transaction_Number AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     (ISNULL(d.Quantity, 0) * -1) AS [Qty], '

    SET @sql = @sql + '     CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '          THEN ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)) / ISNULL(d.Quantity, 0), 2) '
    SET @sql = @sql + '          ELSE 0 '
    SET @sql = @sql + '     END AS [UnitPrice], '
    SET @sql = @sql + '     ROUND((ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0)), 2) AS [Total], '

    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + '         ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '     INNER JOIN AS_Transactions h '
    SET @sql = @sql + '         ON d.AS_Transactions_ID = h.AS_Transactions_ID '
    SET @sql = @sql + '     INNER JOIN dbo.AC_Customers c '
    SET @sql = @sql + '         ON h.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON d.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE d.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND d.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 4 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 23 OR '
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 33 OR '    
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 34 OR '            
    SET @sql = @sql + '        h.Sys_AW_Transaction_Types_ID = 35) '   

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations From Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '        
    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     a.Date_Captured AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(a.From_Bin_New_On_Hand, 0) - ISNULL(a.From_Bin_Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.From_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' UNION ALL '

-------------------------------------------------------------------------------
-- BIN Allocations To Bin
-------------------------------------------------------------------------------

    SET @sql = @sql + ' SELECT '

    SET @sql = @sql + '     a.AW_User_Companies_ID AS [CompanyID], '
    
    SET @sql = @sql + '     p.AP_Products_ID AS [ProductID], '
    SET @sql = @sql + '     p.[Description] AS [Description], '
    SET @sql = @sql + '     p.Product_Code AS [Code], '
    SET @sql = @sql + '     a.Date_Captured AS [Date Captured], '
    SET @sql = @sql + '     ''Bin Allocation'' ' + ' AS [Supplier/Customer], '
    SET @sql = @sql + '     b.Description AS [Bin], '        
    SET @sql = @sql + '     ''BIN ALLOC'' AS [Type], '

    SET @sql = @sql + '     a.Date_Captured AS [Date], '
    SET @sql = @sql + '     CONVERT(varchar(10), a.Batch_No) AS [Ref No], '
	--Speed Issue
    --SET @sql = @sql + '     dbo.fn_AP_BFWD_Inventory_On_Hand(p.AP_Products_ID, ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ') AS [BFWD], '
    SET @sql = @sql + '''' + Convert(varchar(30),@BFWD) + '''' + ' AS [BFWD], '    
    SET @sql = @sql + '     ISNULL(a.To_Bin_New_On_Hand, 0) - ISNULL(a.To_Bin_Previous_On_Hand, 0) AS [Qty], '

    SET @sql = @sql + '     ''0.00'' AS [Unit Price], '
    SET @sql = @sql + '     ''0.00'' AS [Total], '
    SET @sql = @sql + '     RTRIM(LTRIM(ISNULL(u.UserName, ''''))) AS [User] '

    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + '     INNER JOIN AP_Products_Bins_History a '
    SET @sql = @sql + '         ON p.AP_Products_ID = a.AP_Products_ID '
    SET @sql = @sql + '     LEFT JOIN AW_Users u '
    SET @sql = @sql + '         ON a.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + '     LEFT JOIN Lup_AP_Product_Bins b '
    SET @sql = @sql + '         ON b.Lup_AP_Product_Bins_ID = a.To_Lup_AP_Product_Bins_ID '

    SET @sql = @sql + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(10), @ProductID) + ' '
    SET @sql = @sql + '   AND a.Date_Captured >= ' + '''' + CONVERT(varchar(30), @StartDate)  + '''' + ' '
    SET @sql = @sql + '   AND a.Movement_Source = ''BIN ALLOC'' ' 

    SET @sql = @sql + ' ORDER BY [CompanyID], [Date Captured] '

--PRINT @sql

EXEC (@sql)
Go
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Lookup_Editor_Data_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Lookup_Editor_Data_Select]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AW_Lookup_Editor_Data_Select
--Purpose       :Selects Lookup table data for Lookup Editor
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Mods          :18/06/02 - Added Slu_AB_Account_Categories definition fields
--              :11/07/02 - Added Sys_AW_Tax_Codes
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table and its new columns
--              :09/07/03 - Added Sys_AW_Payment_Methods table (Autowiel !!)
--              :08/01/04 - Added System Lookups for Credit Manager
--              :29/02/04 - Added Lup_AS_CBilling_Types
--              :29/02/04 - Added Lup_AP_Fail_Reasons
--              :01/03/04 - Removed Date_Captured & User_ID from Inflections
--              :04/03/04 - Added Server, User and Password to Lup_AS_CBilling_Types
--              :09/03/04 - Added Lup_AP_Claim_Codes
--              :15/07/04 - Added Lup_AC_Customer_Groups
--2004.2.4      :31/05/05 - Added Terms_Value AS [Terms Days] in Slu_AW_Credit_Terms
--2004.2.7      :19/03/06 - Added Slu_AW_SMS_Messages
--2004.2.10     :19/03/06 - Added ORDER BY in @Choice = 'Sys_AB_Account_Categories'
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories
--2004.3.7      :23/07/07 - Added Lup_AC_Markup_Categories and Lup_AP_Markup_Groups
--              :23/09/07 - Added Lup_AB_Account_Groups
--              :28/09/07 - Added Lup_AB_Account_Divisions
--2004.3.8      :24/01/08 - Added Lup_AO_Supplier_Groups and Lup_AO_Supplier_Types
--              :04/05/08 - Added ORDER BY [Description] to most Lookups
--              :10/05/08 - Removed Min GP% field from Lup_AP_Product_Departments
--2004.3.9      :22/06/08 - Added Slu_AW_Shipping_Rates
--2004.4.0      :09/07/08 - Added Slu_AS_Volume_Discounts
--2004.4.1      :08/09/08 - Added Sys_AB_B2, Sys_AB_B3, Sys_AB_I3, Sys_AB_I4
--2004.4.3      :08/03/09 - Re-Indented ALL Lookups
--              :17/03/09 - Added Slu_AC_Statement_Messages
--2004.4.5      :29/05/09 - Added AW_Messages for Credit Manager Messages
--              :16/06/09 - Added Lup_AS_Procurement_Providers for Procurement Providers
--2004.4.8      :19/02/10 - Added Lup_AB_Transaction_Type_Maps for Bank Transaction Types Mapping
--2004.4.9      :07/09/10 - Added Lup_AP_Shipping_Agents for Shipping Agents
--2004.5.1      :18/05/11 - Added Lup_AF_Instructions for Factory Casing Tracking system
--2004.5.7-RGL  :2012-09-17 - Added Country_Dialing_Code column to Slu_AW_Countries
--2004.5.7-RGL  :2012-09-17 - Added Slu_AW_Countries_Mobile
--2004.5.7-RGL  :2012-10-12 - Added Slu_AW_Weight
--2015.6.2-RGL  :2015-11-12 - Added Lup_AP_Product_Bins
--2015.6.2-RGL  :2016-06-24 - Added Lup_AB_Account_Departments
------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AW_Lookup_Editor_Data_Select]
	(
		@Choice varchar(50),
		@CompanyID int
	)
AS
    IF @Choice = 'Sys_AB_Account_Categories'
    	SELECT Sys_AB_Account_Categories_ID as [ID],
               Description as [Description],
               Sys_AB_B1_ID as [BS1],
               Sys_AB_B2_ID as [BS2],
               Sys_AB_B3_ID as [BS3],
               Sys_AB_I1_ID as [IS1],
               Sys_AB_I2_ID as [IS2],
               Sys_AB_I3_ID as [IS3],
               Sys_AB_I4_ID as [IS4],
               Sys_AB_Account_Types_ID as [Type],
               Notes
    	FROM Sys_AB_Account_Categories
        ORDER BY Sys_AB_B1_ID,
                 Sys_AB_B2_ID,
                 Sys_AB_B3_ID,
                 Sys_AB_I1_ID,
                 Sys_AB_I2_ID,
                 Sys_AB_I3_ID,
                 Sys_AB_I4_ID
    ELSE
    IF @Choice = 'Slu_AW_Active'
    	SELECT Slu_AW_Active_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User] 
    	FROM Slu_AW_Active
    ELSE
    IF @Choice = 'Lup_AC_Asset_Types'
    	SELECT Lup_AC_Asset_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Asset_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Banks'
    	SELECT Slu_AW_Banks_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Banks
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Branch_Codes'
    	SELECT Lup_AW_Branch_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Branch_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AS_Card_Institutions'
    	SELECT Slu_AS_Card_Institutions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Cashiers'
    	SELECT Lup_AS_Cashiers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Cashiers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Commission_Categories'
    	SELECT Lup_AS_Commission_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Commission_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Commission_Groups'
    	SELECT Lup_AP_Commission_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Commission_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Cost_Centers'
    	SELECT Lup_AB_Cost_Centers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Cost_Centers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Countries'
    	SELECT Slu_AW_Countries_ID as [ID],
               Description as [Description],
               Country_Code2 as [Country Code2],
               Country_Code3 as [Country Code3],
               Country_Number as [Country Number],
               Country_Dialing_Code as [Country Dialing Code],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Countries
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Credit_Terms'
    	SELECT Slu_AW_Credit_Terms_ID as [ID],
               Description as [Description],
               Terms_Value AS [Terms Days],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Credit_Terms
    ELSE
    IF @Choice = 'Slu_AW_Currencies'
    	SELECT Slu_AW_Currencies_ID as [ID],
               Description as [Description],
               Exchange_Rate as [Exchange Rate],
               Rate_Date as [Rate Date],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Currencies
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Types'
    	SELECT Lup_AC_Customer_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Discount_Categories'
    	SELECT Lup_AC_Discount_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Discount_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Discount_Groups'
    	SELECT Lup_AP_Discount_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Discount_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Inflections'
    	SELECT Slu_AW_Inflections_ID as [ID],
               Alternate1 as [Alternate1],
               Alternate2 as [Alternate2],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Inflections
        ORDER BY [Alternate1]
    ELSE
    IF @Choice = 'Slu_AW_Languages'
    	SELECT Slu_AW_Languages_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Mass_Codes'
    	SELECT Lup_AP_Mass_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Mass_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Months'
    	SELECT Slu_AW_Months_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Months
    ELSE
    IF @Choice = 'Lup_AP_PLU_Tabs'
    	SELECT Lup_AP_PLU_Tabs_ID as [ID],
               Tab_No as [Tab No],Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_PLU_Tabs
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
   ELSE 
   IF @Choice = 'Lup_AP_Product_Departments'
    	SELECT Lup_AP_Product_Departments_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Departments
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Groups'
    	SELECT Lup_AP_Product_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Locations'
    	SELECT Lup_AP_Product_Locations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Locations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Purchase_Categories'
    	SELECT Lup_AP_Purchase_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Purchase_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Manufacturers'
    	SELECT Lup_AP_Product_Manufacturers_ID as [ID],
               Description as [Description],
               Old_Code as [Old Code],
               Default_Supplier_ID as [Default Supplier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Manufacturers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Types'
    	SELECT Lup_AP_Product_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Provinces'
    	SELECT Slu_AW_Provinces_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Provinces
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Purchase_Price_Types'
    	SELECT Lup_AO_Purchase_Price_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Purchase_Price_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Reps'
    	SELECT Lup_AS_Reps_ID as [ID],
               Description as [Description],
               Lup_AS_Commission_Categories_ID as [Commission Category],
        	   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Reps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Rounding_Codes'
    	SELECT Lup_AP_Rounding_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Rounding_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Sales_Areas'
    	SELECT Lup_AC_Sales_Areas_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Sales_Areas
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AP_Sell_By_Codes'
    	SELECT Lup_AP_Sell_By_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Sell_By_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Stores'
    	SELECT Lup_AW_Stores_ID as [ID],
               Description as [Description],
               Slu_AW_Countries_ID as [Country],
               Slu_AW_Provinces_ID as [Province],
               City as [City],Suburb as [Suburb],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Stores
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Switch2_Types'
    	SELECT Lup_AP_Switch2_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Switch2_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Tills'
    	SELECT Lup_AS_Tills_ID as [ID],
               Description as [Description],
               Till_Float as [Till Float],
               Cashier_ID as [Cashier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Tills
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Titles'
    	SELECT Slu_AW_Titles_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Transaction_Profiles'
    	SELECT Lup_AS_Transaction_Profiles_ID as [ID],
               KeyCode as [KeyCode],
               Description as [Description],
               Sequence as [Sequence],
               Activated as [Activated],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Transaction_Profiles
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AP_Units_Of_Measure'
    	SELECT Slu_AP_Units_Of_Measure_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AP_Units_Of_Measure
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Workstations'
    	SELECT Lup_AW_Workstations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Workstations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Years'
    	SELECT Slu_AW_Years_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Years
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_YesNo'
    	SELECT Slu_AW_YesNo_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_YesNo
    ELSE
    IF @Choice = 'Sys_AW_Tax_Codes'
    	SELECT Sys_AW_Tax_Codes_ID as [ID],
               Description as [Description],
               Tax_Code as [Tax Code],
               Tax_Rate as [Tax Rate]
    	FROM Sys_AW_Tax_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Sys_AW_Payment_Methods'
    	SELECT Sys_AW_Payment_Methods_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Sys_AW_Payment_Methods
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Adverse_Reasons'
    	SELECT Slu_AC_Adverse_Reasons_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Adverse_Reasons
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Association_Types'
    	SELECT Slu_AC_Association_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Association_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Auditor_Rankings'
    	SELECT Slu_AC_Auditor_Rankings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Auditor_Rankings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bank_Codes'
    	SELECT Slu_AC_Bank_Codes_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Bank_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bond_Types'
    	SELECT Slu_AC_Bond_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Bond_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Business_Types'
    	SELECT Slu_AC_Business_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Business_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_ITC_Scores'
    	SELECT Slu_AC_ITC_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_ITC_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_KI_Scores'
    	SELECT Slu_AC_KI_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_KI_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Principal_Types'
    	SELECT Slu_AC_Principal_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Principal_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Profession_Types'
    	SELECT Slu_AC_Profession_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Profession_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Ratings'
    	SELECT Slu_AC_Ratings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Ratings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Security_Types'
    	SELECT Slu_AC_Security_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Security_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Shareholding_Types'
    	SELECT Slu_AC_Shareholding_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Shareholding_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Courts'
    	SELECT Slu_AW_Courts_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Courts
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Industry_Categories'
    	SELECT Slu_AW_Industry_Categories_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Industry_Categories
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Info_Report_Types'
    	SELECT Slu_AW_Info_Report_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Info_Report_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Lawsuit_Types'
    	SELECT Slu_AW_Lawsuit_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Lawsuit_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Nature_Of_Action'
    	SELECT Slu_AW_Nature_Of_Action_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Nature_Of_Action
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_CBilling_Providers'
    	SELECT Lup_AS_CBilling_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_CBilling_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Fail_Reasons'
    	SELECT Lup_AP_Fail_Reasons_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Fail_Reasons
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Claim_Codes'
    	SELECT Lup_AP_Claim_Codes_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Claim_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Groups'
    	SELECT Lup_AC_Customer_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               [User_ID] as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_SMS_Messages'
    	SELECT Slu_AW_SMS_Messages_ID as [ID],
               English as [English],
               Afrikaans as [Afrikaans],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_SMS_Messages
        ORDER BY [English]
    ELSE
    IF @Choice = 'Lup_AC_Markup_Categories'
    	SELECT Lup_AC_Markup_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Markup_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Markup_Groups'
    	SELECT Lup_AP_Markup_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Markup_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Groups'
    	SELECT Lup_AB_Account_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Divisions'
    	SELECT Lup_AB_Account_Divisions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Divisions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Groups'
    	SELECT Lup_AO_Supplier_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Types'
    	SELECT Lup_AO_Supplier_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Shipping_Rates'
        SELECT Slu_AW_Shipping_Rates_ID as [ID],
                Post_Code as [Post Code],
                Description as [Description],
                Location as [Locality],
                Rate_Per_Kg as [Rate/Kg],
                Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Shipping_Rates
        ORDER BY [Post Code], [Description]
    ELSE
    IF @Choice = 'Slu_AS_Volume_Discounts'
    	SELECT Slu_AS_Volume_Discounts_ID as [ID],
               Description as [Description],
               Sales_Qty as [Sales Qty],
               Discount_Perc as [Discount %],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Volume_Discounts
    ELSE
    IF @Choice = 'Sys_AB_B2'
    	SELECT Sys_AB_B2_ID as [BS2],
               Description as [Description]
    	FROM Sys_AB_B2
    ELSE
    IF @Choice = 'Sys_AB_B3'
    	SELECT Sys_AB_B3_ID as [BS3],
               Description as [Description]
    	FROM Sys_AB_B3
    ELSE
    IF @Choice = 'Sys_AB_I3'
    	SELECT Sys_AB_I3_ID as [IS3],
               Description as [Description]
    	FROM Sys_AB_I3
    ELSE
    IF @Choice = 'Sys_AB_I4'
    	SELECT Sys_AB_I4_ID as [IS4],
               Description as [Description]
    	FROM Sys_AB_I4
    ELSE
    IF @Choice = 'Slu_AC_Statement_Messages'
    	SELECT Slu_AC_Statement_Messages_ID as [ID],
               Description as [Description],
               Message as [Message],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Statement_Messages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'AW_Messages'
    	SELECT AW_Messages_ID as [ID],
               Description as [Description]
    	FROM AW_Messages
        ORDER BY [ID]
    ELSE
    IF @Choice = 'Lup_AS_Procurement_Providers'
    	SELECT Lup_AS_Procurement_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Procurement_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Transaction_Type_Maps'
    	SELECT Lup_AB_Transaction_Type_Maps_ID as [ID],
               Slu_AW_Banks_ID as [Bank],
               Sys_AB_Transaction_Types_ID as [Transaction Type],
               Mapping_CSV as [Mapping CSV List],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Transaction_Type_Maps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Bank], [Mapping CSV List]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agents'
    	SELECT Lup_AP_Shipping_Agents_ID as [ID],
               Description as [Description],
               Customer_Code as [Customer Code],
               Warehouse_No as [Warehouse No],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agents
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agent_Files'
    	SELECT Lup_AP_Shipping_Agent_Files_ID as [ID],
               Lup_AP_Shipping_Agents_ID as [Shipping Agent],
               Description as [Description],
               Server_Name as [Server Name],
               Login_Name as [Login Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agent_Files
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AF_Instructions'
    	SELECT Lup_AF_Instructions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AF_Instructions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Slu_AW_Countries_Mobile'
    	SELECT Slu_AW_Countries_Mobile_ID as [ID],
               Slu_AW_Countries_ID as [Country],
               Description as [Description],
               Mobile_Dialing_Code as [Mobile Code],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Slu_AW_Countries_Mobile
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AP_AW_Weight'
    	SELECT Lup_AP_AW_Weight_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AP_AW_Weight
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AP_Product_Bins'
    	SELECT Lup_AP_Product_Bins_ID as [ID],
               Description as [Description],
               Email As [Email],
               Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AP_Product_Bins
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AB_Account_Departments'
    	SELECT Lup_AB_Account_Departments_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AB_Account_Departments
        ORDER BY [Description]

GO        

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Statements_Temp_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Statements_Temp_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statements_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of Account Customer Transactions
--              :between month-end Period Procedures 
--Functionality :ONLY Customers that have had transactions are selected
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :09/08/02 - Replaced @Now with (renamed @Date to @DatePicked)
--              :16/08/02 - Added Sys_AW_Transaction_Types_ID = 21 & 22 from
--              :               21=Back Office Receipt, 22=EFT Receipt
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :27/01/03 - Modified @DatePicked to reflect date and ending time
--              :           as at 12 midnight of the date of @DatePicked
--              :15/09/03 - Added @CompanyID in WHERE clause of Customer_Cursor
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.3.2      :13/09/06 - Added update Date_Captured as @Date in AC_Statements_Temp
--              :           and AC_Statement_Details_Temp
--2004.4.2      :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @DatePicked
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
--V6.2	RL	2016-03-30 - Moved Filter to cursor select for speed performance
--V6.2	RL	2016-03-30 - Removed balance <> 0 check. This prevented paid up accounts from displaying for the current month
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Customer_Statements_Temp_Insert]
	(
        @DatePicked DateTime, 
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE
        @LastPeriodProcedureDate DateTime,
        @PeriodProcedureID int,
        @CustomerID int,
        @CustomerName varchar(90),
        @CustomerNumber varchar(10),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @StatementID int,
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @HasBalance tinyint

--	SET @DatePicked = getdate()  --REMOVE THIS: Selected in Statement Print datepicker

--	SET @Now = @DatePicked

--> (27/01/03) Truncates the decimal of today's date e.g.
--        '2002-09-24 13:33:45.076' as '2002-09-24 00:00:00.000',
--        and adds 1 day which equals midnite tonight
--        which returns '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @DatePicked), 0, 1)))

    SET @DatePicked = @Now

    SET @PeriodProcedureID = 0
    SET @HasBalance = 0

--------------------------
-- 	SET @CompanyID = 1
-- 	SET @UserID = 2
--------------------------

--Wipe the TEMP table-------
    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statement_Details_Temp]
        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statements_Temp]
        
        CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
        	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AC_Statements_Temp_ID] [int] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Sys_AW_Transaction_Types_ID] [int] NULL ,
        	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]
        
        CREATE TABLE [dbo].[AC_Statements_Temp] (
        	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Period_Procedures_ID] [int] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL 
        ) ON [PRIMARY]
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'

        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
        
        setuser
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]'

        setuser

    END
----------------------------

    BEGIN
    --> Step 1: Get the date of the LAST Month-End done
    	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date 
    	FROM AW_Period_Procedures 
    	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
    	ORDER BY Month_End_Date DESC
    
        --> Initialize M/E date if this is the FIRST Month-End procedure
    	IF @LastPeriodProcedureDate IS NULL 
    		SET @LastPeriodProcedureDate = '1900/01/01'
   
    --> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @DatePicked,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
    
    --> Step 4: Define a CURSOR for AC_Customers
    	DECLARE Customer_Temp_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AC_Customers_ID,
                    ISNULL(c.Surname, '') +
                    ISNULL(', ' + c.FirstNames, '') AS [FullName],
                    ISNULL(c.Post_Box, ''),
                    ISNULL(c.Post_Office, ''),
                    ISNULL(c.Post_Code, ''),
                    ISNULL(c.Work_Email, ''),
                    ISNULL(c.Customer_Number, '')
                FROM AC_Customers c
                    INNER JOIN AS_Transactions t
                        ON c.AC_Customers_ID = t.AC_Customers_ID                        
    --           WHERE c.AW_User_Companies_ID = @CompanyID     
				--AND ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0      
				--AND (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) 
					
				--V6.2 Added filter here to improve speed	
                --> Show ALL TRANSACTIONS NON-ZERO owing
                WHERE (c.AW_User_Companies_ID = @CompanyID AND
                      (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                       DATEDIFF(d, Transaction_Date, @DatePicked) >= 0)) AND
                     (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) OR

                --> Show CURRENT MONTH transactions that have ZERO owing
                --       from LAST MONTH-END to @DatePicked
                     (c.AW_User_Companies_ID = @CompanyID AND
                     (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) = 0 AND
                      Transaction_Date > @D1 AND
                      DATEDIFF(d, Transaction_Date, @DatePicked) >= 0) AND
                      --Only non cash accounts
                      c.Sys_AC_Account_Types_ID <> 1) AND
                     (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)
            )
    
    	OPEN Customer_Temp_Cursor
    
        	FETCH NEXT FROM Customer_Temp_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @CustomerNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
        		FROM dbo.fn_AC_Customer_Ageing_Values
                    (
                        @CustomerID,
                        @DatePicked,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days

                --> 2004.4.2
                --SET @HasBalance = 0
                
                --V6.2 Already did filtering in cursor select
                --If you check for balance here you will miss paid up accounts for this month
                SET @HasBalance = 1

                --IF @AccountBalance <> 0
                --    BEGIN
                --        SET @HasBalance = 1
                --    END

                --IF @HasBalance = 0
                --    BEGIN
                --        IF @AgeCurrent <> 0 OR
                --            @Age30Days <> 0 OR
                --            @Age60Days <> 0 OR
                --            @Age90Days <> 0 OR
                --            @Age120Days <> 0 OR
                --            @Age150Days <> 0 OR
                --            @Age180Days <> 0
                --            BEGIN
                --                SET @HasBalance = 1
                --            END
                --    END
                    
                IF @HasBalance = 1
                    BEGIN
                		INSERT INTO AC_Statements_Temp
                			(
                                AW_Period_Procedures_ID,
                                AC_Customers_ID,
                                FullName,
                                Customer_Number,
                                Post_Address,
                                Post_Office,
                                Post_Code,
                                Work_Email,
                                [User_ID],
                                AW_User_Companies_ID,
                                Amount,
                                Payment,
                                Account_Balance,
                                [Current],
                                [30Days],
                                [60Days],
                                [90Days],
                                [120Days],
                                [150Days],
                                [180+Days],
                                Date_Captured
                            )
                		VALUES
                			(
                                @PeriodProcedureID,    --initialized to 0 ??
                                @CustomerID,
                                rtrim(ltrim(@CustomerName)),
                                @CustomerNumber,
                                @PostBox,
                                @PostOffice,
                                @PostCode,
                                @WorkEmail,
                                @UserID,
                                @CompanyID,
                                @AgeAmount,
                                @AgePayment,
                                @AccountBalance,
                                @AgeCurrent,
                                @Age30Days,
                                @Age60Days,
                                @Age90Days,
                                @Age120Days,
                                @Age150Days,
                                @Age180Days,
                                @DatePicked
                            )
            
                	  	SELECT @StatementID = Scope_Identity()
                
                		--Insert Transactions since LAST Period Procedure Date
                		INSERT INTO AC_Statement_Details_Temp
                			(
                                AC_Statements_Temp_ID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                Date_Captured,
                                [User_ID],
                                AW_User_Companies_ID
                            )
                        SELECT 
                                @StatementID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Total_Amount,
                                Payment_Amount,
                                @DatePicked,
                                [User_ID],
                                AW_User_Companies_ID
                        FROM AS_Transactions
        --                 WHERE AC_Customers_ID = @CustomerID AND
        --                       ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
        --                       DATEDIFF(d, Transaction_Date, @DatePicked) >= 0 AND
        --                      (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)
        
                        --> Show ALL TRANSACTIONS NON-ZERO owing
                        WHERE (AC_Customers_ID = @CustomerID AND
                              (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 AND
                               DATEDIFF(d, Transaction_Date, @DatePicked) >= 0)) AND
                             (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) OR
        
                        --> Show CURRENT MONTH transactions that have ZERO owing
                        --       from LAST MONTH-END to @DatePicked
                             (AC_Customers_ID = @CustomerID AND
                             (ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) = 0 AND
                              Transaction_Date > @D1 AND
                              DATEDIFF(d, Transaction_Date, @DatePicked) >= 0)) AND
                             (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)

                END
            --> 2004.4.2


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Temp_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CustomerNumber
    
        	END
    	
    	CLOSE Customer_Temp_Cursor
    
    	DEALLOCATE Customer_Temp_Cursor

    END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Statements_Customers_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Statements_Customers_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statements_Customers_Insert
--Purpose       :Saves a snapshot of Account Customer Transactions up to
--              :    the month-end Period Procedure date @ProcedureDate
--Functionality :ONLY Customers that have transactions OWING are selected
--Calls         :fn_AC_Customer_Period_Procedure_Ageing_Values
--Parameters    :
--Date          :2002/03/24
--Authors       :TB
--MODS          :10/07/02 - Remove AC_Customer.Account_Balance field and
--              :           replaced with @AccountBalance = SUM(Ageing_Balances)
--              :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :16/08/02 - Added Sys_AW_Transaction_Types_ID = 21 & 22 from
--              :               21=Back Office Receipt, 22=EFT Receipt
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :31/12/02 - Added Return Code @ReturnCode to validate success
--              :22/01/03 - Added Stock Valuation into NEW Stock_Valuation field
--              :           and insert a STOCK VALUATION at CUSTOMER Month-End
--              :22/01/03 - Added BEGIN TRANSACTION to procedure
--              :15/09/03 - Added @CompanyID in WHERE clause of Customer_Cursor
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.2.9      :14/05/06 - Changed Stock Valuation to use SysOptions setting
--2004.3.2      :13/09/06 - Added update Date_Captured as @Date in AC_Statements
--              :           and AC_Statement_Details
--              :15/09/06 - Rename @Date to @ProcedureDate and replace @Now with
--              :           @ProcedureDate
--              :19/09/06 - Added @ProcedureDate input parameter to in Stock Valuation
--              :           sp_AP_Products_History_Insert. Required for Enterprise
--              :           Stock Valuation
--              :30/09/06 - Replaced fn_AC_Customer_Ageing_Values with Customer Period
--              :           Procedure-specific fn_AC_Customer_Period_Procedure_Ageing_Values
--              :30/09/06 - Changed conditions for INSERT into AC_Statement_Details
--              :           to select only transaction where REMAINING BALANCE <> 0
--              :           and Transaction_Date <= @ProcedureDate
--2004.3.4      :08/03/07 - Removed fetching @LastPeriodProcedureDate - Not used
--2004.4.2      :25/10/08 - Added new Standard Cost Inventory Valuation method
--              :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @ProcedureDate
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
--              :27/11/08 - Added ISNULL validation on all ageing fields
--2004.5.2      :02/07/11 - Add and insert NEW AS_Transactions_ID in AC_Statement_Details
--V6.2	RL	2016-03-30 - Moved Filter to cursor select for speed performance
--V6.2	RL	2016-03-30 - Removed balance <> 0 check. This prevented paid up accounts from displaying for the current month
------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AC_Customer_Statements_Customers_Insert]
	(
        @MonthID int,
        @YearID int,
        @ProcedureDate DateTime, 
        @Description varchar(50),
        @CompanyID int,
        @UserID int
	)

AS

SET NOCOUNT ON

	DECLARE @PeriodProcedureID int,
            @CustomerID int,
            @CustomerName varchar(90),
            @CustomerNumber varchar(10),
            @PostBox varchar(20),
            @PostOffice varchar(30),
            @PostCode varchar(10),
            @WorkEmail varchar(40),
            @AccountBalance money,
            @StatementID int,
            @D1 dateTime,
            @D2 datetime,
            @D3 datetime,
            @D4 datetime,
            @D5 datetime,
            @D6 datetime,
            @D7 datetime,
            @AgePayment money,
            @AgeAmount money,
            @AgeCurrent money,
            @Age30Days money,
            @Age60Days money,
            @Age90Days money,
            @Age120Days money,
            @Age150Days money,
            @Age180Days money,
            @StockValuation money,
            @ValuationMethod smallint,
            @ReturnCode int,
            @HasBalance tinyint


    SET @PeriodProcedureID = 0
    SET @ReturnCode = 0            --0 = Unsuccessful
    SET @HasBalance = 0


    BEGIN TRANSACTION

    --> Stock Valuation (theoretical now)
        SELECT @ValuationMethod = ISNULL(Control_Index, 0)
        FROM Sys_AW_Options
        WHERE Control_Type = 'OptionButton' AND
              Control_Name = 'optInventoryValuation' AND
              Control_Value = 'True' AND
              AW_User_Companies_ID = @CompanyID


        IF @ValuationMethod = 0
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Average_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
    
            END
        ELSE
        IF @ValuationMethod = 1
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Last_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END
        ELSE
        IF @ValuationMethod = 2
            BEGIN
            	SELECT @StockValuation = SUM(ISNULL(Standard_Cost, 0) * ISNULL(On_Hand, 0))
            	FROM AP_Products
                WHERE AW_User_Companies_ID = @CompanyID AND
                      On_Hand <> 0
            END


    --> Step 2: Insert a Period Procedure record and get its ID
    	INSERT AW_Period_Procedures
            (
                Sys_AW_Period_Procedure_Types_ID,
                [Description],
                [Month],
                [Year],
                Month_End_Date,
                Stock_Valuation,
                [User_ID],
                AW_User_Companies_ID
            )
    	VALUES
            (
                1,    -- 1 = Customers Month-End
                @Description,
                @MonthID,
                @YearID,
                @ProcedureDate,
                @StockValuation,                @UserID,
                @CompanyID
            )
    
    	SELECT @PeriodProcedureID = Scope_Identity()


    --> INSERT a STOCK VALUATION
        -----------------------------------------
        EXEC sp_AP_Products_History_Insert 2, @Description, @UserID, @CompanyID, @ProcedureDate


    --> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @ProcedureDate,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
 
 --Select @D1 As '@D1'
    
    --> Step 4: Define a CURSOR for AC_Customers
    	DECLARE Customer_Cursor CURSOR FOR
            (
                SELECT DISTINCT
                    c.AC_Customers_ID,
                    ISNULL(c.Surname, '') +
                    ISNULL(', ' + c.FirstNames, '') AS [FullName],
                    ISNULL(c.Post_Box, ''),
                    ISNULL(c.Post_Office, ''),
                    ISNULL(c.Post_Code, ''),
                    ISNULL(c.Work_Email, ''),
                    ISNULL(c.Customer_Number, '')
				--V6.3 Added filter here to improve speed	
                --> Show ALL TRANSACTIONS NON-ZERO owing
                 FROM AC_Customers c
                    INNER JOIN AS_Transactions t
                        ON c.AC_Customers_ID = t.AC_Customers_ID
                 WHERE c.AW_User_Companies_ID = @CompanyID AND
					(
						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
					 ) AND
                     (
						ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR
						t.Transaction_Date Between @D1 AND @ProcedureDate		--All new transactions
					  )
                
            )
    
    	OPEN Customer_Cursor
    
        	FETCH NEXT FROM Customer_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @CustomerNumber
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
--        		FROM dbo.fn_AC_Customer_Ageing_Values
                FROM dbo.fn_AC_Customer_Period_Procedure_Ageing_Values
                    (
                        @CustomerID,
                        @ProcedureDate,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = ISNULL(@AgeCurrent, 0) + 
                                      ISNULL(@Age30Days, 0) + 
                                      ISNULL(@Age60Days, 0) + 
                                      ISNULL(@Age90Days, 0) + 
                                      ISNULL(@Age120Days, 0) + 
                                      ISNULL(@Age150Days, 0) + 
                                      ISNULL(@Age180Days, 0)

                --> 2004.4.2
                SET @HasBalance = 0
                
                --V6.2 Already did filtering in cursor select
                --If you check for balance here you will miss paid up accounts for this month
                SET @HasBalance = 1

                --IF @AccountBalance <> 0
                --    BEGIN
                --        SET @HasBalance = 1
                --    END

                --IF @HasBalance = 0
                --    BEGIN
                --        IF ISNULL(@AgeCurrent, 0) <> 0 OR
                --            ISNULL(@Age30Days, 0) <> 0 OR
                --            ISNULL(@Age60Days, 0) <> 0 OR
                --            ISNULL(@Age90Days, 0) <> 0 OR
                --            ISNULL(@Age120Days, 0) <> 0 OR
                --            ISNULL(@Age150Days, 0) <> 0 OR
                --            ISNULL(@Age180Days, 0) <> 0
                --            BEGIN
                --                SET @HasBalance = 1
                --            END
                --    END

                IF @HasBalance = 1
                    BEGIN
                		INSERT INTO AC_Statements
                			(
                                AW_Period_Procedures_ID,
                                AC_Customers_ID,
                                FullName,
                                Customer_Number,
                                Post_Address,
                                Post_Office,
                                Post_Code,
                                Work_Email,
                                [User_ID],
                                AW_User_Companies_ID,
                                Amount,
                                Payment,
                                Account_Balance,
                                [Current],
                                [30Days],
                                [60Days],
                                [90Days],
                                [120Days],
                                [150Days],
                                [180+Days],
                                Date_Captured
                            )
                		VALUES
                			(
                                @PeriodProcedureID,
                                @CustomerID,
                                rtrim(ltrim(@CustomerName)),
                                @CustomerNumber,
                                @PostBox,
                                @PostOffice,
                                @PostCode,
                                @WorkEmail,
                                @UserID,
                                @CompanyID,
                                ISNULL(@AgeAmount, 0),
                                ISNULL(@AgePayment, 0),
                                ISNULL(@AccountBalance, 0),
                                ISNULL(@AgeCurrent, 0),
                                ISNULL(@Age30Days, 0),
                                ISNULL(@Age60Days, 0),
                                ISNULL(@Age90Days, 0),
                                ISNULL(@Age120Days, 0),
                                ISNULL(@Age150Days, 0),
                                ISNULL(@Age180Days, 0),
                                @ProcedureDate
                            )
            
                	  	SELECT @StatementID = Scope_Identity()
                
                		--Insert Transactions from LAST Period Procedure Date
                		INSERT INTO AC_Statement_Details
                			(
                                AC_Statements_ID,
                                Transaction_Date,
                                AS_Transactions_ID,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                [User_ID],
                                AW_User_Companies_ID,
                                Date_Captured
                            )
                        SELECT 
                                @StatementID,
                                t.Transaction_Date,
                                t.AS_Transactions_ID,
                                t.Sys_AW_Transaction_Types_ID,
                                t.Transaction_Number,
                                t.Total_Amount,
                                t.Payment_Amount,
                                t.[User_ID],
                                t.AW_User_Companies_ID,
                                @ProcedureDate
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AS_Transactions t
						 WHERE 
							t.AC_Customers_ID = @CustomerID AND
							t.AW_User_Companies_ID = @CompanyID AND 
							(
								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
							 ) AND
							 (
								ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR
								t.Transaction_Date Between @D1 AND @ProcedureDate 	--All new transactions
							  )							
	               END
            --> 2004.4.2


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CustomerNumber
    
        	END
    	
    	CLOSE Customer_Cursor
    
    	DEALLOCATE Customer_Cursor


        SET @ReturnCode = 1


    COMMIT TRANSACTION


SET NOCOUNT OFF


RETURN @ReturnCode
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_IsLevyController]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_IsLevyController]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_IsLevyController
--Purpose       :Select if User is a Levy Controller
--Date          :2016-12-19
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Select_IsLevyController]
    (
        @UserID int,
        @IsLevyController tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SET @IsLevyController = 0

    SELECT @IsLevyController = IsLevyController
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsLevyController IS NULL 
        BEGIN	
    		SET @IsLevyController = 0 
        END

SET NOCOUNT OFF
GO

Delete From Lup_AS_CBilling_Providers Where ISNULL(Description,'') = ''
GO
Update Lup_AS_CBilling_Providers
Set Folder = ''
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],''))) = '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 CBOS Details
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'CBOS'
)
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
	(
		'CBOS',
		'gatekeeper.cbos.co.za',
		'ftppos',
		'!!pos123',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO
--131 sp_AC_Insert_CBilling_Temp
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Insert_CBilling_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Insert_CBilling_Temp]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Insert_CBilling_Temp
--Functionality :INSERT daily UNSUBMITTED Centralised Sales transactions
--Parameters    :
--Date          :2005/09/29
--Authors       :TB
--MODS          :03/10/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
--2004.2.8      :03/05/06 - Added input parameters to EXCLUDE Sales Cost Prices
--              :           and Truck and Tractor SALES data from submission
--2004.3.2      :22/09/06 - Added TRUNCATE all table varchar(50) fields to LEFT(48)
--              :01/11/06 - Added EXCLUDE Lubrication SALES data from submission
--2004.3.4      :21/02/07 - Replaced @chkTruckSales tinyint input parameter with
--              :           @ExclusionsFilter varchar(250) and append to query
--              :24/03/07 - Removed all customer details from submission file
--              :           EXCEPT if FLEET company
--2004.3.5      :16/05/07 - Added FILTER in WHERE clause to EXCLUDE INTER-BRANCH SALES
--              :           to other Customer Group FRANCHISEES in the Bridgestone Retail
--              :           stable by inserting 'bsretail' in the Head_Office field
--              :           of the BRANCH in the Customer Catalog
--2004.3.7      :15/08/07 - Added leading and trailing quotes to Product/Manuf code
--2004.4.7      :18/09/09 - Added Merchant No in 'special_instr'  and replaced 'branch_name'
--              :           with Trading Name as per Denise van Gent new specs
--R.L	2015-03-12	:Added Inclusion List
-------------------------------------------------------------------------------
CREATE PROCEDURE [sp_AC_Insert_CBilling_Temp]
    (
        @chkSalesCost tinyint,
        @chkExcludeInterBranch tinyint,
        @ExclusionsFilter varchar(8000),
        @InclusionFilter varchar(8000),
        @StartDayEndDate datetime,
        @EndDayEndDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql				varchar(8000),
            @RetCode			tinyint,
            @No_Days			int,
            @Temp_No_Days		Varchar(20)

    SET @RetCode = 0
    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
          
    Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
    
    --Select @StartDayEndDate

    SET @sql = ' INSERT AS_Transactions_CBilling_Temp '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + 'AS_Transactions_ID, '
    SET @sql = @sql + 'Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + 'cat_code, '
    SET @sql = @sql + 'drs_acc, '
    SET @sql = @sql + 'trs_ref, '
    SET @sql = @sql + 'trs_date, '
    SET @sql = @sql + 'qty, '
    SET @sql = @sql + 'amount, '
    SET @sql = @sql + 'gls_acc, '
    SET @sql = @sql + 'narr, '
    SET @sql = @sql + 'stock_group, '
    SET @sql = @sql + 'drs_apply, '
    SET @sql = @sql + 'sys_code, '
    SET @sql = @sql + 'updated, '
    SET @sql = @sql + 'interfaced, '
    SET @sql = @sql + 'drs_age_month, '
    SET @sql = @sql + 'stock_code, '
    SET @sql = @sql + 'area, '
    SET @sql = @sql + 'drs_alpha, '
    SET @sql = @sql + 'branch, '
    SET @sql = @sql + 'vat_amount, '
    SET @sql = @sql + 'cost_amount, '
    SET @sql = @sql + 'rep_comm, '
    SET @sql = @sql + 'process_type, '
    SET @sql = @sql + 'rep_code, '
    SET @sql = @sql + 'acct_type, '
    SET @sql = @sql + 'disc_amnt, '
    SET @sql = @sql + 'std_sell_price, '
    SET @sql = @sql + 'drs_trs_code, '
    SET @sql = @sql + 'trs_type, '
    SET @sql = @sql + 'acc_month, '
    SET @sql = @sql + 'acc_year, '
    SET @sql = @sql + 'con_acct_no, '
    SET @sql = @sql + 'zz_int01, '
    SET @sql = @sql + 'cntno, '
    SET @sql = @sql + 'line_disc1, '
    SET @sql = @sql + 'line_disc2, '
    SET @sql = @sql + 'stock_sell1, '
    SET @sql = @sql + 'no_of_deals, '
    SET @sql = @sql + 'zz_date01, '
    SET @sql = @sql + 'zz_date02, '
    SET @sql = @sql + 'zz_date03, '
    SET @sql = @sql + 'special_instr, '
    SET @sql = @sql + 'deals_flag, '
    SET @sql = @sql + 'deals_number, '
    SET @sql = @sql + 'vat_exempt_member, '
    SET @sql = @sql + 'cmonth, '
    SET @sql = @sql + 'cyear, '
    SET @sql = @sql + 'rep_call_status, '
    SET @sql = @sql + 'drsdiv_code, '
    SET @sql = @sql + 'crs_acc, '
    SET @sql = @sql + 'creation_date, '
    SET @sql = @sql + 'creation_time, '
    SET @sql = @sql + 'creation_userid, '
    SET @sql = @sql + 'creation_proc, '
    SET @sql = @sql + 'item_number, '
    SET @sql = @sql + 'rep_code2, '
    SET @sql = @sql + 'qty2, '
    SET @sql = @sql + 'deposit_amount, '
    SET @sql = @sql + 'job_number, '
    SET @sql = @sql + 'line_disc_amnt, '
    SET @sql = @sql + 'carhire_cntno, '
    SET @sql = @sql + 'currency, '
    SET @sql = @sql + 'exch_rate, '
    SET @sql = @sql + 'cyear_month, '
    SET @sql = @sql + 'zz_date04, '
    SET @sql = @sql + 'zz_date05, '
    SET @sql = @sql + 'zz_int02, '
    SET @sql = @sql + 'zz_int03, '
    SET @sql = @sql + 'zz_int04, '
    SET @sql = @sql + 'zz_int05, '
    SET @sql = @sql + 'zz_dec01, '
    SET @sql = @sql + 'zz_dec02, '
    SET @sql = @sql + 'zz_dec03, '
    SET @sql = @sql + 'zz_dec04, '
    SET @sql = @sql + 'zz_dec05, '
    SET @sql = @sql + 'zz_log01, '
    SET @sql = @sql + 'zz_log02, '
    SET @sql = @sql + 'zz_log03, '
    SET @sql = @sql + 'zz_log04, '
    SET @sql = @sql + 'zz_log05, '
    SET @sql = @sql + 'zz_log06, '
    SET @sql = @sql + 'zz_log07, '
    SET @sql = @sql + 'zz_char01, '
    SET @sql = @sql + 'zz_char02, '
    SET @sql = @sql + 'zz_char03, '
    SET @sql = @sql + 'zz_char04, '
    SET @sql = @sql + 'zz_char05, '
    SET @sql = @sql + 'key_glstrs, '
    SET @sql = @sql + 'key_history, '
    SET @sql = @sql + 'dumped, '
    SET @sql = @sql + 'company_name, '
    SET @sql = @sql + 'branch_name, '
    SET @sql = @sql + 'drs_name, '
    SET @sql = @sql + 'crs_name, '
    SET @sql = @sql + 'prd_grp_descr, '
    SET @sql = @sql + 'stk_descry, '
    SET @sql = @sql + 'status_ind, '
    SET @sql = @sql + 'customer_ref, '
    SET @sql = @sql + 'comments1, '
    SET @sql = @sql + 'comments2, '
    SET @sql = @sql + 'comments3, '
    SET @sql = @sql + 'comments4, '
    SET @sql = @sql + 'comments5, '
    SET @sql = @sql + 'comments6, '
    SET @sql = @sql + 'comments7, '
    SET @sql = @sql + 'comments8, '
    SET @sql = @sql + 'database_id, '
    SET @sql = @sql + 'system_id, '
    SET @sql = @sql + 'vat_reg_no, '
    SET @sql = @sql + 'email, '
    SET @sql = @sql + 'customer_cell_number, '
    SET @sql = @sql + 'customer_email_address, '
    SET @sql = @sql + 'Date_Captured, '
    SET @sql = @sql + 'User_ID, '
    SET @sql = @sql + 'AW_User_Companies_ID, '
    SET @sql = @sql + 'Slu_AW_Active_ID '
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' t.AS_Transactions_ID, '
    SET @sql = @sql + ' cb.Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + ' CASE WHEN t.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + ' THEN ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' WHEN t.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ''CR'' + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' END, '                                                        --cat_code
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --trs_ref
    SET @sql = @sql + ' t.Transaction_Date, '                                         --trs_date
    SET @sql = @sql + ' d.Quantity, '                                                 --qty
    SET @sql = @sql + ' ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), '     --amount,
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '      --narr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '     --stock_group
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --drs_apply
    SET @sql = @sql + ' ''"'' + ''SPI'' + ''"'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' 1, '                                                          --drs_age_month

--     SET @sql = @sql + ' CASE WHEN p.Manufacturer_Code IS NULL OR RTRIM(LTRIM(p.Manufacturer_Code)) = ''"'' + ''''   '
--     SET @sql = @sql + ' THEN p.Product_Code '
--     SET @sql = @sql + ' ELSE p.Manufacturer_Code '
--     SET @sql = @sql + ' END, '                                                        --stock_code
    SET @sql = @sql + ' CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(p.Product_Code, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ISNULL(p.Manufacturer_Code, '''') + ''"'' '
    SET @sql = @sql + ' END, '                                                        --stock_code

    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '            --drs_alpha
    SET @sql = @sql + ' ''"'' + ISNULL(uc.Network_Identity_Number, '''') + ''"'', '   --branch
    SET @sql = @sql + ' d.Tax_Amount, '                                               --vat_amount
    
    --> Product Cost Price data = 0
    IF @chkSalesCost = 0
    BEGIN
        SET @sql = @sql + ' 0, '
    END
    ELSE
    BEGIN    
        SET @sql = @sql + ' ROUND(ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0), 2), '    --cost_amount,
    END
    
    SET @sql = @sql + ' 0, '                                                         --rep_comm
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --process_type
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'','
    SET @sql = @sql + ' d.Discount_Amount, '                                         --disc_amnt
    SET @sql = @sql + ' d.Original_Price, '                                          --std_sell_price
    SET @sql = @sql + ' ''"'' + ''100'' + ''"'', '                                   --drs_trs_code
    SET @sql = @sql + ' 1, '                                                         --trs_type
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --acc_month,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --acc_year
    
    --     SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '           --on_acct_no
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(c.Customer_Number, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' 1, '                                                         --zz_int01
    SET @sql = @sql + ' 1, '                                                         --cntno
    SET @sql = @sql + ' CASE WHEN (d.Unit_Price * d.Quantity) <> 0 '
    
    --     SET @sql = @sql + ' THEN CONVERT(money, ABS(ROUND( (((d.Discount_Amount) / (d.Unit_Price * d.Quantity)) * 100), 2)) ) '
    SET @sql = @sql + ' THEN ABS(ROUND(CONVERT(money, ((d.Discount_Amount / (d.Unit_Price * d.Quantity)) * 100)), 2)) '
    
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END, '                                                       --line_disc1
    SET @sql = @sql + ' 0, '                                                         --line_disc2
    SET @sql = @sql + ' 0, '                                                         --stock_sell1
    SET @sql = @sql + ' 0, '                                                         --no_of_deals
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date01
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date02
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date03


--    SET @sql = @sql + ' ''"'' + ''"'', '                                             --special_instr
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Old_Customer_Number, ''''), 10) + ''"'', '        --special_instr


    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_flag
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_number
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --cmonth,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --cyear
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --drsdiv_code,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --crs_acc,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --creation_date,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_time,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_userid,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_proc,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --item_number,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code2,
    SET @sql = @sql + '  0 , '                                                       --qty2,
    SET @sql = @sql + '  0 , '                                                       --deposit_amount,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --job_number,
    SET @sql = @sql + '  0 , '                                                       --line_disc_amnt,
    SET @sql = @sql + '  0 , '                                                       --carhire_cntno,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --currency,
    SET @sql = @sql + '  0 , '                                                       --exch_rate,
    SET @sql = @sql + '  0 , '                                                       --cyear_month,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date04,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date05,
    SET @sql = @sql + '  0 , '                                                       --zz_int02,
    SET @sql = @sql + '  0 , '                                                       --zz_int03,
    SET @sql = @sql + '  0 , '                                                       --zz_int04,
    SET @sql = @sql + '  0 , '                                                       --zz_int05,
    SET @sql = @sql + '  0 , '                                                       --zz_dec01,
    SET @sql = @sql + '  0 , '                                                       --zz_dec02,
    SET @sql = @sql + '  0 , '                                                       --zz_dec03,
    SET @sql = @sql + '  0 , '                                                       --zz_dec04,
    SET @sql = @sql + '  0 , '                                                       --zz_dec05,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char01,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char02,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char03,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char04,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char05,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_glstrs,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_history,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --company_name


--    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --branch_name
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Trading_Name, ''''), 48) + ''"'', '             --branch_name

   
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --drs_name,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + ''"'', '                                                       --crs_name,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '              --prd_grp_descr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '               --stk_descry,
    SET @sql = @sql + ' ''"'' + ''NE'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Registration_No, ''''), 48) + ''"'', '          --customer_ref,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --comments1,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'', '          --comments2,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'', '           --comments3,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'', '             --comments4,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Authorization_No, ''''), 48) + ''"'', '         --comments5,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Odometer_Reading, ''''), 48) + ''"'', '         --comments6,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Engine_No, ''''), 48) + ''"'', '                --comments7,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Model_Year, '''') + ISNULL('' '' + cb.Make, '''') + ISNULL('' '' + cb.Model, ''''), 48) + ''"'', '          --comments8,
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Network_Identity_Number, ''''), 48) + ''"'', '  --system_id,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Tax_Number, ''''), 48) + ''"'', '                --vat_reg_no,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'', '                   --email,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Cell_No, ''''), 48) + ''"'', '                   --customer_cell_number,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'', '                --customer_email_address,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' t.Date_Captured, '
    SET @sql = @sql + ' t.User_ID, '
    SET @sql = @sql + ' t.AW_User_Companies_ID, '
    SET @sql = @sql + ' t.Slu_AW_Active_ID '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '    INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '    LEFT JOIN AS_Transactions_CBilling cb '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = cb.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 Lup_AP_Product_Types pt '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @sql = @sql + '    INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '    INNER JOIN AW_User_Companies uc '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = uc.AW_User_Companies_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 + '    INNER 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 + '    INNER 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 + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '

    IF @chkExcludeInterBranch = 1
        BEGIN
            SET @sql = @sql + '       ISNULL(LOWER(RTRIM(LTRIM(c.Head_Office))), '''') <> ''bsretail'' AND '
        END

    SET @sql = @sql + '      (t.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '       t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '       t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

-- Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
-- Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  

    SET @sql = @sql + 'ORDER BY t.AS_Transactions_ID '

IF LEN(@sql) >= 8000
    BEGIN
        SET @RetCode = 1

        RETURN @RetCode
    END

EXEC (@sql)
--Select @sql
SET @RetCode = 2

RETURN @RetCode
Go

--122 sp_AS_CSales_Submission_INS_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS_SEL
--Purpose       :Select Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	c.Surname AS [Customer Name] '	
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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 + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO

--123 sp_AS_CSales_Submission_REW_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW_SEL
--Purpose       :Select Sales Submission Data For Rewards
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '	WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '   
	SET @sql = @sql + '	ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '	END '
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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_AS_Reps r '
	SET @sql = @sql + '		ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export	
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO

--229 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          :
--RL	V6_1	2015-02-17	:Use froam and to Day End dates sent through
--							:Added Inclusion and Exclusion Checks
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	Declare @CompanyNo			Int,
			@LastDayEnd			DateTime,
			@WhichName			Tinyint,
			@Loop_Ind			Int,
			@ptrval				binary(16),
			@OffSet				Int,
			
			@AS_Transactions_ID	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),
			@Product_Code		Varchar(20),
			
			@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(4000),
			@F_TyreData_2		Varchar(4000),
			@F_TyreData_3		Varchar(4000),
			@F_TyreData_4		Varchar(4000),
			@F_TyreData_5		Varchar(4000),
			@No_Days			Int,
			@Temp_No_Days		Varchar(20),
			@Details_Found		Int,
			@sql				Varchar(8000)
			
	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 Text,
			F_TyreData_2 Varchar(1),
			F_TyreData_3 Varchar(1),
			F_TyreData_4 Varchar(1),
			F_TyreData_5 Varchar(1)
		)

	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'
	
    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
	
	--RL V6_1 Changed to use dates sent through				
	--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	

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	--Exec (@sql)

	
	--Exec (@sql)

	DECLARE Get_Data CURSOR
	FOR
	SELECT
		DISTINCT t.AS_Transactions_ID, t.Transaction_Number, t.Transaction_Date,
		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
	   	 t.Sys_AW_Transaction_Types_ID = 4) AND
    	t.Slu_AW_Active_ID = 1 AND
    	ISNULL(t.Total_Amount,0) <> 0 AND
        t.Day_End >=  @StartDayEndDate AND 
        t.Day_End <= @EndDayEndDate AND
        t.AW_User_Companies_ID = @CompanyID
    	Order By t.Transaction_Date

	--Exec (@sql)
	--Select (@sql)

	OPEN Get_Data
	
	 FETCH NEXT FROM Get_Data INTO
		@AS_Transactions_ID, @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
--Select @AS_Transactions_ID, @StartDayEndDate, @No_Days
		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
		--		LEFT OUTER JOIN AP_Products p
		--			ON d.AP_Products_ID = p.AP_Products_ID
		--WHERE
		--	AS_Transactions_ID = @AS_Transactions_ID AND
		--	ISNULL(d.Extended_Amount,0) <> 0 AND
		--	d.Slu_AW_Active_ID = 1 AND
		--	p.Slu_AW_YesNo_Non_Stock_Item = 0							
		
		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
		SET @F_Vehicle_Reg_No = @Comment
		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,',','~') + ','
								'XXXXXXXXXXXXXXXXX' + ','

		SET @Details_Found = 0
		SET @F_NoOfTyres = '0'
		
	SET @sql = 'DECLARE Get_Detail CURSOR '
	SET @sql = @sql + ' FOR '
	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + '		ISNULL(d.Quantity,0), ISNULL(d.Extended_Amount,0), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Description,''''))), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Product_Code,''''))) '
	SET @sql = @sql + ' FROM '
	SET @sql = @sql + '		AS_Transaction_Details d '
	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 Lup_AP_Product_Departments pd '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '		INNER 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 + '		INNER 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 + '		INNER 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 + ' WHERE '
	SET @sql = @sql + '	d.AS_Transactions_ID = ' + CONVERT(varchar(30), @AS_Transactions_ID) + ' AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 '
			
	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
--Select @sql
	Exec (@sql)
				
	 	OPEN Get_Detail
		
		FETCH NEXT FROM Get_Detail INTO
			@Quantity, @Extended_Amount, @Product_Description, @Product_Code
			
		WHILE @@FETCH_STATUS = 0
		BEGIN
				
--Select 		@AS_Transactions_ID, @Quantity, @Extended_Amount, @Product_Description, @Product_Code

	
			SET @Details_Found = 1
			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
			
			SET @F_NoOfTyres = Convert(Varchar(10), ( Convert(Decimal(9,3),@F_NoOfTyres) + @Quantity ) )
			
			WHILE @Loop_Ind <= @Quantity
			BEGIN
				IF Len(@F_TyreData_1) < 3850
				BEGIN
					SET @F_TyreData_1 = @F_TyreData_1 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				ELSE
				IF (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2)<3850)
				BEGIN
					SET @F_TyreData_2 = @F_TyreData_2 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				
				SET @Loop_Ind = @Loop_Ind+1
			END
		
			FETCH NEXT FROM Get_Detail INTO
				@Quantity, @Extended_Amount, @Product_Description, @Product_Code
		END
		CLOSE Get_Detail
		Deallocate Get_Detail

		IF NOT (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2) >= 3850)
		BEGIN
			IF @Details_Found = 1
			BEGIN
				SET @F_TyreData_1 = REPLACE(@F_TyreData_1, 'XXXXXXXXXXXXXXXXX', @F_NoOfTyres)
			
				INSERT INTO @Tbl_F(F_TyreData_1) Values(@F_TyreData_1+@F_TyreData_2+@F_TyreData_3+@F_TyreData_4+@F_TyreData_5)
			END
		END
	
		FETCH NEXT FROM Get_Data INTO
			@AS_Transactions_ID, @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

SET NOCOUNT OFF
GO

--230 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]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
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),
			@sql					Varchar(8000)
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	--SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') FROM AW_User_Companies
     
    SET @OLD_Transaction_Number = '' 
                      	
   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
			
	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
	
	SET @sql = '        DECLARE Get_Data CURSOR FOR '
	SET @sql = @sql + '	SELECT '
	SET @sql = @sql + '		CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '		WHEN 3 THEN ''' + 'IN' +  ''' '
	SET @sql = @sql + '		WHEN 4 THEN ''' + 'CN' +  ''' '
	SET @sql = @sql + '		ELSE ''' + 'UN' +  ''' '
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(t.Transaction_Number,''''), '					--Transaction Number
	SET @sql = @sql + '		CONVERT(Varchar(10),t.Transaction_Date,112), '		--Transaction Date
	SET @sql = @sql + '		CONVERT(Varchar(5),t.Transaction_Date,108), '			--Transaction Time
	SET @sql = @sql + '		CONVERT(VARCHAR(20),IsNull(t.Lup_AS_Reps_ID,0)), '	--Transaction Rep ID
	SET @sql = @sql + '		CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '		WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '     
	SET @sql = @sql + '		ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(p.Product_Code,''''), '							--Product Code
	SET @sql = @sql + '		ISNULL(p.[Description],''''), '							--Product Description
	SET @sql = @sql + '		CONVERT(Varchar(20),ISNULL(d.Quantity,0)) '			--Quantity
	SET @sql = @sql + '		FROM ' 
	SET @sql = @sql + '		AS_Transactions t '
	SET @sql = @sql + '		INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '			ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_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 + '		INNER 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 + '		INNER 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 + '		INNER 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 + '	WHERE ' 
	SET @sql = @sql + '		(t.Sys_AW_Transaction_Types_ID = 3  OR '      -- Invoices
	SET @sql = @sql + '		 t.Sys_AW_Transaction_Types_ID = 4)  AND '    -- Refunds	
	SET @sql = @sql + '     t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   			
	SET @sql = @sql + '		t.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		t.Total_Amount <> 0 AND '
	SET @sql = @sql + '		p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'	
    SET @sql = @sql + '		t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '		t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '		

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
	SET @sql = @sql + '	ORDER BY t.Transaction_Date ' 	  	
--	Select @sql
	Exec (@sql)
	
	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

--231 sp_AS_CSales_Submission_INS_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS_SEL
--Purpose       :Select Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	c.Surname AS [Customer Name] '	
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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 + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO


--232 sp_AS_CSales_Submission_REW_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW_SEL
--Purpose       :Select Sales Submission Data For Rewards
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    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

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '	WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '   
	SET @sql = @sql + '	ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '	END '
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.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 + '	INNER 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 + '	INNER 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 + '	INNER 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_AS_Reps r '
	SET @sql = @sql + '		ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
	SET @sql = @sql + '	c.Sys_AC_Account_Types_ID Not In (3,5,6,7) AND'   -- 3 Inter-Company, 5 Trade, 6 Consignment, 7 Export	
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Add_Product_To_Order_Candidates_RET]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Add_Product_To_Order_Candidates_RET]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Add_Product_To_Order_Candidates_RET
--Purpose       :Check if @ProductID exists in Order Candidates
--				:If EXISTS then UPDATE else ADD new Candidate
--Date          :13 JAN 2002
--Authors       :TB
--MODS          :13/10/03 - Added @RemoteID input parameter
--2004.3.7      :22/11/07 - Added using Standard_Cost as @Unit_Cost if 
--              :           chkProcureStdCostPricing parameter = '1'
--              :24/11/07 - Added Select CURRENT SELLING if @Unit_Cost = 0
--RL	V6.3	:2017-02-09 - Added return value AO_Order_Candidates_ID to be used in sales order
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Add_Product_To_Order_Candidates_RET]
    (
       	@ProductID int,
       	@SuppliersID int = 0,
    	@Qty decimal(9,3) = 0,
       	@Notes varchar(50) = null,
       	@Originator int,
       	@User_ID int,
       	@CompanyID int,
        @RemoteID int
    )
AS

SET NOCOUNT ON

    DECLARE @AO_Order_Candidates_ID int,
            @Unit_Cost money,
            @ExistingID int,
            @Last_Qty decimal(9,3),
            @Last_Reviews int,
            @UseStdCost varchar(250),
			@ExistingNote varchar(50)
            
    BEGIN	
    	SELECT @ExistingID = AO_Order_Candidates_ID,
               @Last_Qty = Qty,
               @Last_Reviews = Reviews,
			   @ExistingNote = Notes
    	FROM AO_Order_Candidates
    	WHERE AP_Products_ID = @ProductID AND
    		  AO_Suppliers_ID = @SuppliersID AND
    		  AW_User_Companies_ID = @CompanyID

    	
--     	SELECT @Unit_Cost = Last_Cost
--     	FROM AP_Products
--     	WHERE AP_Products_ID = @ProductID AND
--     		  AW_User_Companies_ID = @CompanyID	

        -------------------------------------------------------
    --> Get Use Product Standard Cost in Procurement Manager Unit Pricing parameter
        -------------------------------------------------------
        SELECT @UseStdCost = ISNULL(Control_Value, '')
        FROM Sys_AW_Options
        WHERE Control_Type = 'CheckBox' AND
              Control_Name = 'chkProcureStdCostPricing' AND
              Control_Index = 0 AND
              AW_User_Companies_ID = @CompanyID


        IF @UseStdCost = '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Standard_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END

            IF @Unit_Cost = 0
                BEGIN
                	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
                	FROM AP_Products
                	WHERE AP_Products_ID = @ProductID AND
                		  AW_User_Companies_ID = @CompanyID
                END

        IF @UseStdCost <> '1'
            BEGIN
            	SELECT @Unit_Cost = ISNULL(Last_Cost, 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END


        IF @Unit_Cost = 0
            BEGIN
                SELECT @Unit_Cost = ISNULL(dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1, Price2_Effective_Date, Price2_Price1, getdate()), 0)
            	FROM AP_Products
            	WHERE AP_Products_ID = @ProductID AND
            		  AW_User_Companies_ID = @CompanyID
            END
        -------------------------------------------------------
--Select @ExistingID As '@ExistingID'
    	IF @ExistingID is NULL
    	BEGIN
    		EXEC @ExistingID = sp_AO_Insert_Order_Candidates	@ProductID,
																@SuppliersID,
																@Qty,
																@Unit_Cost,
																@Notes,
																1,
																@Originator,
																@User_ID,
																@CompanyID,
																@RemoteID
                                               
			--SELECT @ExistingID = Scope_Identity()
		END
    	ELSE
    	BEGIN
			IF @ExistingNote Like '%Back Order - %'
			BEGIN
				IF @Notes Like '%Back Order - %'
				BEGIN
					SELECT @Notes = REPLACE(@Notes, 'Back Order - ',', ')

					SELECT @Notes = LEFT(@ExistingNote + @Notes,50)
				END
			END
		 
    		UPDATE AO_Order_Candidates							
    		SET Qty = @Last_Qty + @Qty,
    			Last_Cost = @Unit_Cost,
    			Reviews = @Last_Reviews + 1,
    			Notes = @Notes,
    			Originator = @Originator,
    			[User_ID] = @User_ID
    		WHERE AO_Order_Candidates_ID = @ExistingID
		END

    END
RETURN @ExistingID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Insert_Sales_Order_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Insert_Sales_Order_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Insert_Sales_Order_Details
--Purpose       :
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
--RL	V6.3	:2017-02-09 - Added automaticaly add back order products to order Candidates
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Insert_Sales_Order_Details]
    (
        @CustomerID int,
    	@ProductID int,
    	@Description varchar(50),
    	@ProductCode varchar(20),
    	@Quantity decimal(9, 3),
    	@BackOrder decimal(9, 3),
    	@OriginalPrice money,
    	@UnitPrice money,
    	@DiscountAmount money,
    	@Amount money,
    	@Shipping money,
        @Tax_Rate decimal(9, 3),
    	@TaxAmount money,
    	@ExtendedAmount money,
    	@UnitCost money,
        @PromoProductID int,
    	@PromoPrice money,
    	@DateCaptured datetime,
    	@AddToBO int,
    	@Customer_Reference varchar(15),
		@Lup_AP_Product_Bins_ID int,
       	@UserID int,
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @NewOrderID int
    
    DECLARE @AO_Suppliers_ID		int,
			@RemoteID				int,
			@AO_Order_Candidates_ID int,
			@Notes					varchar(50),
			@Customer_Name			varchar(40)		

    INSERT AS_Sales_Order_Details
        (
            AC_Customers_ID,
            AP_Products_ID,
            [Description],
            Product_Code,
            Quantity,
            Back_Order,
            Original_Price,
            Unit_Price,
            Discount_Amount,
            Amount,
            Shipping_Cost,
            Tax_Rate,
            Tax_Amount,
            Extended_Amount,
            Unit_Cost,
            AP_Promotion_Products_ID,
            Promo_Price,
            Date_Captured,
            User_ID,
            AW_User_Companies_ID,
            Customer_Reference,
			Lup_AP_Product_Bins_ID
        )
    VALUES
        (
            @CustomerID,
            @ProductID,
            @Description,
            @ProductCode,
            @Quantity,
            @BackOrder,
            @OriginalPrice,
            @UnitPrice,
            @DiscountAmount,
            @Amount,
            @Shipping,
            @Tax_Rate,
            @TaxAmount,
            @ExtendedAmount,
            @UnitCost,
            @PromoProductID,
            @PromoPrice,
            @DateCaptured,
            @UserID,
            @CompanyID,
            @Customer_Reference,
			@Lup_AP_Product_Bins_ID
        )

	SELECT @NewOrderID = Scope_Identity()

RETURN @NewOrderID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Delete_Sales_Order_Item]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Delete_Sales_Order_Item]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AS_Delete_Sales_Order_Item
--Purpose       :Delete a Sales Order item from AS_Sales_Order_Details
--Date          :08 JUN 2008
--Authors       :TB
--MODS          :
--RL	V6.3	:2017-02-09 - Remove 
---------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Delete_Sales_Order_Item]
    (
        @OrderID				int,
		@AP_Products_ID		    int,
		@Back_Order				decimal(18,3)
    )
AS

SET NOCOUNT ON

	IF @AP_Products_ID <> 0
	BEGIN
		DECLARE @AO_Order_Candidates_ID int,
				@Order_Qty				decimal(9,3)

		SET @AO_Order_Candidates_ID = 0
		SET @Order_Qty = 0
	
		SELECT	@Order_Qty = Qty,
				@AO_Order_Candidates_ID = AO_Order_Candidates_ID
		FROM AO_Order_Candidates
		WHERE AP_Products_ID = @AP_Products_ID
		AND Slu_AW_Active_ID = 1

		--If the sales order raised a Order Candidate we need to remove the qty ordered
		IF @AO_Order_Candidates_ID <> 0
		BEGIN
			--If the Order candidate still exists
			IF @Order_Qty <> 0
			BEGIN
			
				--If Order canidate has the same or less quantity as the back order we can remove the order candidate
				IF (( @Order_Qty = @Back_Order) or (@Order_Qty < @Back_Order) )
				BEGIN
			
					DELETE FROM AO_Order_Candidates WHERE AO_Order_Candidates_ID = @AO_Order_Candidates_ID
			
				END
				ELSE
				BEGIN
					UPDATE AO_Order_Candidates 
					SET Qty = Qty - @Back_Order
					WHERE AO_Order_Candidates_ID = @AO_Order_Candidates_ID
				END
			
			END
		END
	END

	DELETE 
	FROM AS_Sales_Order_Details
	WHERE AS_Sales_Order_Details_ID = @OrderID

GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Update_Sales_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Update_Sales_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Update_Sales_Orders
--Purpose       :
--Date          :2017-02-09
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Update_Sales_Orders]
    (
    	@AO_GRV_ID	int,
		@ProductID	int,
    	@Qty		Decimal(18,3),
       	@CompanyID	int
    )
AS

SET NOCOUNT ON

	DECLARE @AS_Transaction_Details_ID		Int,
			@Back_Order						Decimal(18,3),
			@Sales_Order_BO_Qty				Decimal(18,3),
			@Received_Qty					Decimal(18,3),
			@Apply_Qty						Decimal(18,3),
			@Transaction_Number				Varchar(19),
			@Notes							Varchar(500),
			@Found							Int

	SET @Received_Qty = @Qty

	DECLARE GetData CURSOR
	FOR
	SELECT 
			AS_Transaction_Details_ID, 
			Back_Order,
			Transaction_Number
	FROM AS_Transactions h
		INNER JOIN AS_Transaction_Details d
			ON h.AS_Transactions_ID = d.AS_Transactions_ID
	WHERE	h.Sys_AW_Transaction_Types_ID = 16 AND
			AP_Products_ID = @ProductID AND
			Back_Order <> 0 AND
			Lup_AP_Product_Bins_ID = 1	--Only Product Bin 1, GRV Defaults to 1
	ORDER BY h.Date_Captured ASC

	OPEN GetData

	FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @Back_Order, @Transaction_Number
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @Notes = ''
		SET @Found = 0

		IF @Back_Order <= @Qty
		BEGIN
	
			SET @Apply_Qty = @Back_Order
		
			UPDATE AS_Transaction_Details
			SET Back_Order = 0,
				Quantity = Quantity + @Apply_Qty
			WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID
		
			SELECT @Notes = Notes
			FROM AO_GRV
			WHERE AO_GRV_ID = @AO_GRV_ID

			IF @Notes = ''
			BEGIN
				SET @Notes = 'Sales Order Replenished: ' + @Transaction_Number
			END
			ELSE
			BEGIN
				SELECT @Found = CHARINDEX(@Transaction_Number, @Notes)

				IF @Found = 0
					SELECT @Notes = @Notes + ', ' + @Transaction_Number
			END

			UPDATE AO_GRV
			SET Notes = @Notes
			WHERE AO_GRV_ID = @AO_GRV_ID

		END
		ELSE
		IF @Back_Order > @Qty
		BEGIN
	
			UPDATE AS_Transaction_Details
			SET Back_Order = Back_Order - @Qty,
				Quantity = Quantity + @Qty
			WHERE AS_Transaction_Details_ID = @AS_Transaction_Details_ID
		
			SELECT @Notes = Notes
			FROM AO_GRV
			WHERE AO_GRV_ID = @AO_GRV_ID

			IF @Notes = ''
			BEGIN
				SET @Notes = 'Sales Order Replenished: ' + @Transaction_Number
			END
			ELSE
			BEGIN
				SELECT @Found = CHARINDEX(@Transaction_Number, @Notes)

				IF @Found = 0
					SELECT @Notes = @Notes + ', ' + @Transaction_Number
			END

			UPDATE AO_GRV
			SET Notes = @Notes
			WHERE AO_GRV_ID = @AO_GRV_ID

		END
	
		FETCH NEXT FROM GetData INTO @AS_Transaction_Details_ID, @Back_Order, @Transaction_Number
	END
	CLOSE GetData
	DEALLOCATE GetData
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Clear_CBilling_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Clear_CBilling_Temp]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AC_Clear_CBilling_Temp
--Functionality :DROP and CREATE sp_AC_Clear_CBilling_Temp
--Date          :2005/10/03
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Clear_CBilling_Temp]

AS

SET NOCOUNT ON


        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AS_Transactions_CBilling_Temp]
        
        
        CREATE TABLE [dbo].[AS_Transactions_CBilling_Temp] (
        	[AS_Transactions_CBilling_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AS_Transactions_ID] [int] NULL ,
        	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
        	[cat_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_date] [datetime] NULL ,
        	[qty] [decimal](18,3) NULL ,
        	[amount] [money] NULL ,
        	[gls_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[narr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[stock_group] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_apply] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[sys_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[updated] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[interfaced] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_age_month] [smallint] NULL ,
        	[stock_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[area] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_alpha] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[branch] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_amount] [money] NULL ,
        	[cost_amount] [money] NULL ,
        	[rep_comm] [money] NULL ,
        	[process_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[rep_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[acct_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[disc_amnt] [money] NULL ,
        	[std_sell_price] [money] NULL ,
        	[drs_trs_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[trs_type] [smallint] NULL ,
        	[acc_month] [smallint] NULL ,
        	[acc_year] [smallint] NULL ,
        	[con_acct_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_int01] [smallint] NULL ,
        	[cntno] [smallint] NULL ,
        	[line_disc1] [decimal](18, 3) NULL ,
        	[line_disc2] [decimal](18, 3) NULL ,
        	[stock_sell1] [money] NULL ,
        	[no_of_deals] [smallint] NULL ,
        	[zz_date01] [datetime] NULL ,
        	[zz_date02] [datetime] NULL ,
        	[zz_date03] [datetime] NULL ,
        	[special_instr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[deals_flag] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[deals_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_exempt_member] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[cmonth] [smallint] NULL ,
        	[cyear] [smallint] NULL ,
        	[rep_call_status] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drsdiv_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[crs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_date] [datetime] NULL ,
        	[creation_time] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_userid] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[creation_proc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[item_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[rep_code2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[qty2] [decimal](18,3) NULL ,
        	[deposit_amount] [decimal](18, 3) NULL ,
        	[job_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[line_disc_amnt] [decimal](18, 3) NULL ,
        	[carhire_cntno] [smallint] NULL ,
        	[currency] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[exch_rate] [money] NULL ,
        	[cyear_month] [smallint] NULL ,
        	[zz_date04] [datetime] NULL ,
        	[zz_date05] [datetime] NULL ,
        	[zz_int02] [smallint] NULL ,
        	[zz_int03] [smallint] NULL ,
        	[zz_int04] [smallint] NULL ,
        	[zz_int05] [smallint] NULL ,
        	[zz_dec01] [decimal](18,3) NULL ,
        	[zz_dec02] [decimal](18,3) NULL ,
        	[zz_dec03] [decimal](18,3) NULL ,
        	[zz_dec04] [decimal](18,3) NULL ,
        	[zz_dec05] [decimal](18,3) NULL ,
        	[zz_log01] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log02] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log03] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log04] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log05] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log06] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_log07] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char01] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char02] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char03] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[zz_char05] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[key_glstrs] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[key_history] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[dumped] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[company_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[branch_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[drs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[crs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[prd_grp_descr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[stk_descry] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[status_ind] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments3] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments4] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments5] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments6] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments7] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[comments8] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[database_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[system_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[vat_reg_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[email] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_cell_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[customer_email_address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
        
        
        ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AS_Transactions_CBilling_Temp] PRIMARY KEY  CLUSTERED 
        	(
        		[AS_Transactions_CBilling_Temp_ID]
        	)  ON [PRIMARY] 
        
        
        ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] ADD 
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_acc] DEFAULT ('SPIRAL') FOR [drs_acc],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_gls_acc] DEFAULT ('N/A') FOR [gls_acc],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_sys_code] DEFAULT ('SPI') FOR [sys_code],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_updated] DEFAULT ('no') FOR [updated],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_interfaced] DEFAULT ('no') FOR [interfaced],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_area] DEFAULT ('N/A') FOR [area],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_acct_type] DEFAULT ('N/A') FOR [acct_type],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_trs_code] DEFAULT ('100') FOR [drs_trs_code],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_vat_exempt_member] DEFAULT ('no') FOR [vat_exempt_member],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_rep_call_status] DEFAULT ('no') FOR [rep_call_status],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log01] DEFAULT ('no') FOR [zz_log01],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log02] DEFAULT ('no') FOR [zz_log02],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log03] DEFAULT ('no') FOR [zz_log03],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log04] DEFAULT ('no') FOR [zz_log04],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log05] DEFAULT ('no') FOR [zz_log05],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log06] DEFAULT ('no') FOR [zz_log06],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log07] DEFAULT ('no') FOR [zz_log07],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_dumped] DEFAULT ('no') FOR [dumped],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_status_ind] DEFAULT ('NE') FOR [status_ind],
        	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_database_id] DEFAULT ('SPIRAL') FOR [database_id]
        
        
        setuser
        
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling_Temp].[AW_User_Companies_ID]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AS_Transactions_CBilling_Temp].[Date_Captured]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[drs_age_month]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling_Temp].[Slu_AW_Active_ID]'
        
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[trs_type]'
        
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling_Temp].[User_ID]'
        
        
        setuser
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_Current_AS_Transaction_Headers_SUM]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Current_AS_Transaction_Headers_SUM]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


----------------------------------------------------------------------------
--Description	:sp_Current_AS_Transaction_Headers_SUM
--Purpose       :Day End Sales Shape - GetCompletedDE (Completed Day Ends)
--Date			:2017/02/24
--Authors		:RL
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_Current_AS_Transaction_Headers_SUM]
	(
		@CompanyID int,
        @TranDate datetime
	)

AS

SET NOCOUNT ON

	SELECT    
		tt.[Description] AS [Transaction Type],	
		SUM(ISNULL(t.Amount,0)) as [Amount], 	
		SUM(ISNULL(t.Total_Cost,0)) as [Cost], 	
        SUM(ISNULL(t.Total_Tax_Amount,0)) as [Tax], 
		SUM(ISNULL(t.Total_Discount_Amount,0)) as [Discount],         
		SUM(ISNULL(t.Total_Amount,0)) as [Total], 
		SUM(ISNULL(t.Payment_Amount,0)) as [Payment]
	FROM AS_Transactions t 
	    LEFT JOIN Sys_AW_Transaction_Types tt
            ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID 
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
	WHERE t.AW_User_Companies_ID = @CompanyID AND
          t.Day_End IS NULL
          AND t.Transaction_Date <= @TranDate
    GROUP BY tt.[Description]      
    ORDER BY tt.[Description]

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Delivery_Address_Hist]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Delivery_Address_Hist]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Delivery_Address_Hist
--Purpose       :Select address details used by customer
--Functionality :Select address details used by customer
--Date          :2013-01-02
--Authors       :RL
--V6.3	RL	2017-03-07	:Select Record per transaction
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
    (    	    	
    	@AC_Customers_ID int
    )
AS 

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

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

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

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


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

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

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

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

EXEC (@sql)
--Select @sql

GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Profit_Protector]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Profit_Protector]
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Profit_Protector
--Purpose       :Filters Products to set Product flags globally
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2004/02/14
--Authors       :TB
--Version       :1.0.0
--MODS          :30/07/04 - Removed @Option parameter and UI Supplier OptionBox
--2004.3.8      :30/11/07 - Added new @optShowGP input parameter to calc GP% and
--              :           also show relavent Cost Price as [Cost]
--              :09/04/08 - Added [Retail] field (Selling - Max Disc%)
--              :10/04/08 - Added elimate all products not Active
--              :09/05/08 - Replaced Maximum Discount% field functionality with
--              :           Minimum GP% functionality and replaced existing columns
--              :           with [Min Retail] and [Max Disc%]
--2004.4.1      :29/09/08 - Added Purchase Category
--V6.3	RL	2017-03-14	:Added check to see if Max_Discount_Perc = 100. Changed to 0. Gives divide by Zero error
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Filter_Profit_Protector]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
    	@PurchCatID int = -1,
        @optShowGP tinyint = 1
	)

AS

SET NOCOUNT ON

	DECLARE @Filter varchar(8000),
            @sql varchar(8000)

	SET @Filter = ''
    SET @sql = ''


    --> Products_Suppliers
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' s.AO_Suppliers_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
    --> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
    --> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
    --> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
    --> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
    --> Purchase Category
	IF @PurchCatID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchCatID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchCatID)
		END


	BEGIN
		IF @Filter = ''
			SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)
		ELSE
			SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                            convert(varchar(20), @CompanyID)


-- NEW 2004.3.8
        SET @Filter = @Filter + ' AND p.Slu_AW_Active_ID = 1 '


    	SET @sql = 'SELECT '
        SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
        SET @sql = @sql + ' p.[Description] AS [Description], '
        SET @sql = @sql + ' p.Product_Code AS [Code], '

        -----------------------------------------------------------------
        -- Cost
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Average_Cost, 0) AS [Cost], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Last_Cost, 0) AS [Cost], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
                SET @sql = @sql + ' ISNULL(p.Standard_Cost, 0) AS [Cost], '
            END

        -----------------------------------------------------------------
        -- Std GP%
        -----------------------------------------------------------------
        SET @sql = @sql + ' CONVERT(money, dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate())) AS [Selling], '

        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Average_Cost, 0))) AS [Std GP%], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Last_Cost, 0))) AS [Std GP%], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
                SET @sql = @sql + ' CONVERT(money, dbo.GetGrossMargin(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate(), ISNULL(p.Standard_Cost, 0))) AS [Std GP%], '
            END


        SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Price AS [Edit Price], '
        SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
        SET @sql = @sql + ' p.Max_Discount_Perc AS [Min GP%], '

        -----------------------------------------------------------------
        -- Min Retail
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Average_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Average_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Last_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Last_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
           END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
            BEGIN
 				SET @sql = @sql + ' CASE ' 
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Standard_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0))))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' ELSE '
                SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN ISNULL(p.Standard_Cost, 0) > 0 '
                SET @sql = @sql + '		 THEN CONVERT(money, ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0)))  ) '
                SET @sql = @sql + '		 ELSE 0.00 '
                SET @sql = @sql + '      END '
                SET @sql = @sql + ' END AS [Min Retail], '
            END

        -----------------------------------------------------------------
        -- Max Discount %
        -----------------------------------------------------------------
        -- Use Average Cost
        IF @optShowGP = 0
            BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Average_Cost, 0) + (ISNULL(p.Average_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END

        -- Use Last Cost
        ELSE
        IF @optShowGP = 1
            BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Last_Cost, 0) + (ISNULL(p.Last_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END

        -- Use Standard Cost
        ELSE
        IF @optShowGP = 2
			BEGIN
				SET @sql = @sql + ' CASE '
				SET @sql = @sql + ' WHEN ISNULL(p.Max_Discount_Perc, 0) < 100 '
				SET @sql = @sql + ' THEN '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - ISNULL(p.Max_Discount_Perc, 0)))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' ELSE '
				SET @sql = @sql + '		 CASE '
				SET @sql = @sql + '		 WHEN dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) <> 0 '
                SET @sql = @sql + '      THEN CONVERT(money, ((dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) - (ISNULL(p.Standard_Cost, 0) + (ISNULL(p.Standard_Cost, 0) * (ISNULL(p.Max_Discount_Perc, 0) / (100 - 0))))) / dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) * 100) ) '
                SET @sql = @sql + '      ELSE 0.00 '
                SET @sql = @sql + '      END '
				SET @sql = @sql + ' END AS [Max Disc%], '
            END
        -----------------------------------------------------------------

        SET @sql = @sql + ' p.Slu_AW_YesNo_Max_Discount_Perc AS [Apply Min%] '

        SET @sql = @sql + ' FROM AP_Products p '
        SET @sql = @sql + '     INNER JOIN AO_Suppliers s '
        SET @sql = @sql + '         ON s.AO_Suppliers_ID = p.Default_Supplier_ID '
        SET @sql = @sql + @Filter
        SET @sql = @sql + ' ORDER BY p.[Description] '

		EXEC (@sql)
--SELECT @sql
	END

SET NOCOUNT OFF	
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_RPT_Invoice_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Invoice_Print
--Purpose       :POS Invoice printing
--Parameters    :
--Date          :2002/04/12
--Authors       :TB
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses from Physical to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :18/07/02 - Added Discount % per Line Item as [DetailDiscPerc]
--              :10/09/02 - Convert Discount % per Line from SMALLMONEY to MONEY
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :26/05/03 - Added ISNULL validation to customer address fields
--              :26/05/03 - Added Cell/Home/Work telephone number (next to Post Code)
--              :09/07/03 - Added Tax_Number (VATNo) effective 1 APR 2004 per SARS
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--              :09/02/04 - Added [JobSource] to print any JOBCARD source docs
--              :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :17/08/04 - Added p.Pack_Mass to aggregate invoice load mass
--              :21/12/04 - Added XREF to Sys_AW_Payment_Methods and PRINT
--              :08/01/05 - Added [JobRefNo] to print on new MAXIPREST layout
--              :02/02/05 - Added [TextMessage] to print on all invoice documents
--              :19/05/05 - Removed Payment Method from primary SELECT and pre-fetch
--2004.2.4      :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.1      :21/08/09 - Rearranged order of telephone numbers: Work/Cell/Home
--2004.3.2      :08/10/06 - Added [SerialNo] fields
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--              :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :05/07/08 - Renamed Job XRef from AS_Transaction_Sources
--              :           from 'Jobcard No: ' to 'Sales Order/Job No: '
--2004.4.5      :18/07/09 - Converted into DYNAMIC script to include NEW
--              :           POS Document Print Order of items settings
--2004.4.8      :17/04/10 - Reworked setting DEFAULT message and Added new QUOTE message
--2004.5.0      :26/01/11 - Added [Emails] for all customer e-mail addresses
--              :26/01/11 - Added [CompanyEmail] for company e-mail address
--2004.5.3      :18/07/11 - Added REPLACE syntax to REMOVE single APOSTROPHE in MESSAGES text
--2004.5.7 RGL  :2012-09-20 - Added check to to print tradeing name with company name
--2004.5.8 RGL  :2013-02-20 - Fixed check to to print tradeing name with customer and not company name
--RL	V6.0	:2014-01-28 - Use product print description instead of description
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.0	:2014-07-19 - Return TDHeader & TDDetail
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
--RL	V6.3	:2017-03-21 - Reworked Reg_No And Millage
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
    (
    	@TransactionID int
    )
AS

SET NOCOUNT ON

    DECLARE @SortOrder tinyint,
            @TranTypeID tinyint,
            @Message varchar(100),
            @DefaultMessage varchar(100),
            @QuoteMessage varchar(100),
            @PrintDefaultMessage varchar(10),
            @PrintQuoteMessage varchar(10),
            @OrderFilter tinyint,
            @sql varchar(8000)
            
	DECLARE @Customer_Name varchar(100),
 			@Inv_Address1 varchar(40),
 			@Inv_Address2 varchar(40),
 			@Inv_City varchar(30),
			@Inv_Code varchar(10),
			@Tax_Number varchar(16),
			@AW_YesNo_Invoice tinyint,
			
			@Delivery_Address varchar(40),
			@Delivery_Suburb varchar(40),
			@Delivery_City varchar(30),
			@Delivery_Post_Code varchar(10),
			@AW_YesNo_Delivery_Address tinyint,
			@AC_Customers_ID int
            
    --> 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 '

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

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

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

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

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

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

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

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

    SET @sql = @sql + ' td.Discount_Amount AS [DetailDiscount] , '
    SET @sql = @sql + ' (td.Unit_Price * (td.Quantity + td.Back_Order)) + td.Discount_Amount AS [DetailAmount], '
    SET @sql = @sql + ' td.Tax_Amount AS [DetailTaxAmount], '
    SET @sql = @sql + ' td.Extended_Amount AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime], '
    SET @sql = @sql + ' u.UserName AS [UserCode], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    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], '
	SET @sql = @sql + ' ISNULL(ca.Reg_No, '''') AS [Reg_No], '
	SET @sql = @sql + ' ISNULL(ca.Mileage, '''') AS [Mileage] '	

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

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

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF
GO
IF 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, Folder, Date_Captured, User_ID, AW_User_Companies_ID, Slu_AW_Active_ID)
	VALUES('Innovation Group', 'spiralsoft.co.za', 'HiQss', '@H1Q$p1r@1#', '', GETDATE(), 1, 1, 1)
END
GO
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Innovation Group',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'HiQss',
	Login_Password = '@H1Q$p1r@1#',
	Folder = ''
WHERE Description = 'Innovation Group'
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Enterprise_Product_Search_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Enterprise_Product_Search_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Enterprise_Product_Search_Lups
--Purpose       :Returns ONLY ACTIVE Lookups
--Date          :2006/10/14
--Authors       :TB
--MODS:         :
--2004.3.4      :27/02/07 - Added Option 10 Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector lookup fields
--              :           [Edit Price], [Edit Disc], [Apply Max]
--2004.3.8      :09/05/08 - Replaced [Apply Max] with [Min GP%]
--2004.5.7 RGL  :2012-11-01 - Added 14 - Levy, 15 Weight
--2016.6.3 RL	:2017-03-30 - Removed check to see if lookup field is enabled. 
--				 It is irrelevant. Product should be loaded even if lookup value is disabled
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Enterprise_Product_Search_Lups]
    (
    	@Option int
    )

AS

SET NOCOUNT ON

    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name

    
    --> Manufacturer
    	ELSE 
    	IF @Option = 2
    		SELECT Lup_AP_Product_Manufacturers_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Manufacturers
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Type
    	ELSE 
    	IF @Option = 3
    		SELECT Lup_AP_Product_Types_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Types
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Group
    	ELSE 
    	IF @Option = 4
    		SELECT Lup_AP_Product_Groups_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Groups
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Department
    	ELSE 
    	IF @Option = 5
    		SELECT Lup_AP_Product_Departments_ID AS [ID], 
    			[Description] 
    		FROM Lup_AP_Product_Departments
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    --> Location
    	ELSE 
    	IF @Option = 6
    		SELECT Lup_AP_Product_Locations_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Product_Locations
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Active
    	ELSE 
    	IF @Option = 7
    		SELECT Slu_AW_Active_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_Active

    --> Model Types
    	ELSE 
    	IF @Option = 8
    		SELECT Lup_AP_Switch2_Types_ID AS [ID],
    		   [Description] 
    		FROM Lup_AP_Switch2_Types

    --> GL Accounts
        ELSE 
    	IF @Option = 9
        	SELECT AB_Accounts_ID AS [ID], 
               [Description]
        	FROM AB_Accounts 
--        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Purchase Category
    	ELSE 
    	IF @Option = 10
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID],
    			[Description] 
    		FROM Lup_AP_Purchase_Categories
--            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]

    --> Edit Price
    	ELSE 
    	IF @Option = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Edit Disc
    	ELSE 
    	IF @Option = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Apply Min GP%
    	ELSE 
    	IF @Option = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo
    		
    --> Levy
    	ELSE 
    	IF @Option = 14
            SELECT AP_Products_ID AS [ID],
    		      [Description]
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY [Description] ASC

    --> Weight
    	ELSE             
    	IF @Option = 15
        	SELECT Lup_AP_AW_Weight_ID AS [ID], 
               [Description]
        	FROM Lup_AP_AW_Weight
--        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
            

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Latest_Transactions]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Latest_Transactions]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Latest_Transactions
--Purpose       :POS ALL latest <n> transactions
--Date          :2011/09/04
--Authors       :TB
--MODS:         :
--V6.3	RL	2017/04/04	:Added transaction note so I can display window if note exists for conformation
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AS_POS_Latest_Transactions]
    (
        @CompanyID int,
        @TopNo smallint
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT TOP ' + CONVERT(varchar(10), @TopNo) + ' '

    SET @sql = @sql + ' h.AS_Transactions_ID AS [TranID], '
    SET @sql = @sql + ' h.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' h.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' ISNULL(tt.[Description], '''') AS [Type], '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL(c.Surname, ''''))) + '
    SET @sql = @sql + ' RTRIM(LTRIM(ISNULL('' '' + c.Firstnames, ''''))) + '
    SET @sql = @sql + ' ''('' + RTRIM(LTRIM(CONVERT(varchar(10), c.AC_Customers_ID))) + '')'' AS [Customer], '
    SET @sql = @sql + ' h.Transaction_Date AS [Date], '
    SET @sql = @sql + ' h.Transaction_Number AS [Doc No], '
    SET @sql = @sql + ' ISNULL(h.Comment, '''') AS [Asset], '
    SET @sql = @sql + ' ISNULL(h.Total_Amount, 0) AS [Amount], '
    SET @sql = @sql + ' ISNULL(h.Customer_Reference, '''') AS [Order No], '
    SET @sql = @sql + ' ISNULL(u.UserName, '''') AS [Cashier], '
    SET @sql = @sql + ' h.Slu_AW_Active_ID AS [ActiveID], '
    SET @sql = @sql + ' ISNULL(m.Comment, '''') AS [TransactionComment] '

    SET @sql = @sql + ' FROM AS_Transactions h '
    SET @sql = @sql + '      LEFT 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.Lup_AS_Cashiers_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Comments m '
    SET @sql = @sql + '          ON h.AW_Comments_ID = m.AW_Comments_ID '


    SET @sql = @sql + ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' '
    SET @sql = @sql + '  AND (h.Sys_AW_Transaction_Types_ID = 1 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 2 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 13 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 16 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 17 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 23 '
    SET @sql = @sql + '    OR h.Sys_AW_Transaction_Types_ID = 24) '


    SET @sql = @sql + ' ORDER BY h.AS_Transactions_ID DESC '


--PRINT @sql

EXEC (@sql)
GO
--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
Update AB_Accounts
Set Description = 'UNKNOWN-'+Cast(AB_Accounts_ID As Varchar(10))
Where IsNull(Description,'') = ''
Go
Update AP_Products
Set Levy_Weight_ID = 1
Where ISNULL(Levy_Weight_ID,0) = 0
GO
UPDATE AP_Products
SET Levy_Weight_ID = 1
WHERE ISNULL(Levy_Weight_ID,0) = 0
GO
UPDATE AP_Products
SET Slu_AW_YesNo_Sell_Below_Cost = 0
WHERE Slu_AW_YesNo_Sell_Below_Cost IS NULL
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Product_Update_Export]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Product_Update_Export]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_Update_Export
--Purpose       :Filters Product Update Products to Export
--Date          :2006/05/11
--Authors       :TB
--MODS          :
--2004.3.2      :11/09/06 - Added @LocationID input parameter and [Location] field
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :29/12/06 - Uncommented AP_Products_ID in SELECT to enable UPDATE RS
--              :           of sugFilterProducts in UI
--              :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--              :09/05/08 - Replaced [Max Disc] with [Min GP%] and [Apply Max] with [Apply Min%]
--              :09/05/08 - Added ALIAS to Profit Protector fields - unaliased caused wrong
--              :           values to be fetched !!!
--2004.4.0      :19/07/08 - Added NOT EDITABLE p.Last_Sale_Date AS [Last Sale] AS LAST COLUMN
--              :19/07/08 - Added @chkSortOrder input parameter to sort by [Last Sale]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--2004.5.7 RGL  :2012-11-01 - Added [Levy], [Weight Type], [Weight]
--V6.3	RL	2017/04/06	:Added single product search
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Filter_Product_Update_Export]
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
    	@SupplierID int = -1,
    	@LocationID int = -1,
    	@PurchaseCatID int = -1,
    	@chkDateCaptured tinyint = -1,
    	@DateCaptured datetime,
    	@chkActiveOnly tinyint = -1,
    	@chkSortOrder tinyint = 0,
    	@Product	varchar(50) = ''
	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @sql varchar(8000)


	SET @Filter = ''
    SET @sql = ''


--> Manufacturer
	IF @ManufacturerID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufacturerID)
		END
--> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
--> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
--> Department
	IF @DepartmentID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
--> Supplier
	IF @SupplierID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
--> Location
	IF @LocationID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
		END
--> Purchase Category
	IF @PurchaseCatID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseCatID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AP_Purchase_Categories_ID = ' +
                                convert(varchar(20), @PurchaseCatID)
		END
--> Product
	IF @Product <> '' 
		BEGIN
			SET @Product =  '%' +  @Product + '%'
			IF @Filter = ''
				SET @Filter = ' WHERE ' + '( p.Description Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Product_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.SKU_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Supercession Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code1 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code2 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Keywords Like ' + '''' + @Product + '''' + ' )' 
			ELSE
				SET @Filter = @Filter + ' AND ' + '( p.Description Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Product_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.SKU_Code Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Supercession Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code1 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Alternate_Code2 Like ' + '''' + @Product + '''' + ' ' +
							  ' OR ' + ' p.Keywords Like ' + '''' + @Product + '''' + ' )' 
		END

                          --' AND h.Transaction_Date > ' + '''' + CONVERT(varchar(30), @LastDayEnd) + '''' +  ' '
                          
                          
                          
--> Company
	IF @Filter = ''
		SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)
	ELSE
		SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)


--> Fetch only Products from this Date Captured and later
    IF @chkDateCaptured = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
            ELSE
                SET @Filter = @Filter + '  AND p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
        END


--> Fetch only ACTIVE Products
    IF @chkActiveOnly = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Slu_AW_Active_ID = 1 '
            ELSE
                SET @Filter = @Filter + '  AND p.Slu_AW_Active_ID = 1 '
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Product Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' p.Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' p.SKU_Code AS [SKU Code], '
    SET @sql = @sql + ' p.Alternate_Code1 AS [Alt Code], '
    SET @sql = @sql + ' p.Alternate_Code2 AS [Bar Code], '
    SET @sql = @sql + ' p.Lup_AP_Product_Manufacturers_ID AS [Manufacturer], '
    SET @sql = @sql + ' p.Manufacturer_Code AS [Manuf Code], '
    SET @sql = @sql + ' p.Manufacturer_Description AS [Manuf Desc], '
    SET @sql = @sql + ' p.Default_Supplier_ID AS [Supplier], '
    SET @sql = @sql + ' p.Lup_AP_Product_Types_ID AS [Type], '
    SET @sql = @sql + ' p.Lup_AP_Product_Groups_ID AS [Group], '
    SET @sql = @sql + ' p.Lup_AP_Product_Departments_ID AS [Department], '
    SET @sql = @sql + ' p.Lup_AP_Product_Locations_ID AS [Location], '
--    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [Purchase Cat], '
    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [PurchaseCat], '    
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg Cost], '
    SET @sql = @sql + ' p.Standard_Cost AS [Std Cost], '
    SET @sql = @sql + ' p.Price1_Effective_Date AS [Price1 Date], '
    SET @sql = @sql + ' p.Price1_Price1 AS [Price 1-1], '
    SET @sql = @sql + ' p.Price1_Price2 AS [Price 1-2], '
    SET @sql = @sql + ' p.Price2_Effective_Date AS [Price2 Date], '
    SET @sql = @sql + ' p.Price2_Price1 AS [Price 2-1], '
    SET @sql = @sql + ' p.Price2_Price2 AS [Price 2-2], '
    SET @sql = @sql + ' p.Pack_Volume AS [Volume], '
    SET @sql = @sql + ' p.Pack_Mass AS [Mass], '
    SET @sql = @sql + ' p.Slu_AW_Active_ID AS [Active], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Price AS [Edit Price], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
    SET @sql = @sql + ' p.Max_Discount_Perc AS [Min GP%], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Max_Discount_Perc AS [Apply Min%], '
    SET @sql = @sql + ' p.Last_Sale_Date AS [Last Sale], '
    SET @sql = @sql + ' p.Levy_AP_Product_ID AS [Levy], '
    SET @sql = @sql + ' p.Lup_AP_AW_Weight_ID AS [WeightType], '
    SET @sql = @sql + ' p.Product_Weight AS [Weight] '        
    
    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + @Filter

    IF @chkSortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY p.[Description] '
        END

    IF @chkSortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY p.Last_Sale_Date DESC '
        END


	EXEC (@sql)
--Select @sql
SET NOCOUNT OFF	
Go
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Add_Product_To_Sales_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Add_Product_To_Sales_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Add_Product_To_Sales_Orders
--Purpose       :Check if @ProductID EXISTS in Sales Orders
--				:If EXISTS then UPDATE else ADD new Sales Orders
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
--V6.3	RL	2017/04/06	:Added option to automaticaly add backorder items to shopping list
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Add_Product_To_Sales_Orders]
    (
        @CustomerID int,
    	@ProductID int,
    	@Description varchar(50),
    	@ProductCode varchar(20),
    	@Quantity decimal(9, 3),
    	@BackOrder decimal(9, 3),
    	@OriginalPrice money,
    	@UnitPrice money,
    	@DiscountAmount money,
    	@Amount money,
    	@Shipping money,
        @Tax_Rate decimal(9, 3),
    	@TaxAmount money,
    	@ExtendedAmount money,
    	@UnitCost money,
        @PromoProductID int,
    	@PromoPrice money,
    	@DateCaptured datetime,
    	@AddToBO int,
    	@Customer_Reference varchar(15),
		@Lup_AP_Product_Bins_ID int,
       	@UserID int,
       	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @ExistingID int,
			
            @Last_Qty decimal(9,3),
            @Last_Disc money,
            @Last_Shipping money,
            @Last_BOQty decimal(9,3),
            @New_Qty decimal(9,3),
            @New_BOQty decimal(9,3),
			@New_TotalQty decimal(9,3),
            @New_Disc money,
            @New_Shipping money,
            @SubTotal money,
            @Tax money,
            @Total money,

			@AO_Suppliers_ID		int,
			@RemoteID				int,
			@AO_Order_Candidates_ID int,
			@Notes					varchar(50),
			@Customer_Name			varchar(40)		

    SELECT @ExistingID = AS_Sales_Order_Details_ID,
            @Last_Qty = Quantity,
            @Last_BOQty = Back_Order,
            @Last_Disc = Discount_Amount,
            @Last_Shipping = Shipping_Cost
    FROM AS_Sales_Order_Details
    WHERE AP_Products_ID = @ProductID AND
    		AC_Customers_ID = @CustomerID AND
    		AW_User_Companies_ID = @CompanyID AND
    		Customer_Reference = @Customer_Reference AND
			Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

    IF @ExistingID is NULL
    BEGIN
    	EXEC sp_AS_Insert_Sales_Order_Details
                                    @CustomerID,
                                    @ProductID,
                                    @Description,
                                    @ProductCode,
                                    @Quantity,
                                    @BackOrder,
                                    @OriginalPrice,
                                    @UnitPrice,
                                    @DiscountAmount,
                                    @Amount,
                                    @Shipping,
                                    @Tax_Rate,
                                    @TaxAmount,
                                    @ExtendedAmount,
                                    @UnitCost,
                                    @PromoProductID,
                                    @PromoPrice,
                                    @DateCaptured,
                                    @AddToBO,
                                    @Customer_Reference,
									@Lup_AP_Product_Bins_ID,
                                    @UserID,
                                    @CompanyID
	END
    ELSE
	BEGIN
		--> COMBINE the new sales order with existing
        SET @New_Qty = @Last_Qty + @Quantity
        SET @New_Disc = ROUND(@Last_Disc + @DiscountAmount, 2)
        SET @New_Shipping = ROUND(@Last_Shipping + @Shipping, 2)
        SET @New_BOQty = @Last_BOQty + @BackOrder
        SET @New_TotalQty = @New_Qty + @New_BOQty

        SET @SubTotal = ROUND((@UnitPrice * @New_TotalQty) - @New_Disc, 2)
        SET @Tax = ROUND((@SubTotal + @New_Shipping) * (@Tax_Rate / 100), 2)
        SET @Total = ROUND(@SubTotal + @Tax, 2)


    	UPDATE AS_Sales_Order_Details							
    	SET [Description] = @Description,
            Product_Code = @ProductCode,
            Quantity = @New_Qty,
            Back_Order = @New_BOQty,
            Original_Price = @OriginalPrice,
            Unit_Price = @UnitPrice,
            Discount_Amount = @New_Disc,
            Amount = @SubTotal,
            Shipping_Cost = @New_Shipping,
            Tax_Rate = @Tax_Rate,
            Tax_Amount = @Tax,
            Extended_Amount = @Total,
            Unit_Cost = @UnitCost,
            AP_Promotion_Products_ID = @PromoProductID,
            Promo_Price = @PromoPrice,
            Date_Captured = @DateCaptured,
            [User_ID] = @UserID,
            AW_User_Companies_ID = @CompanyID
    	WHERE AS_Sales_Order_Details_ID = @ExistingID   		
	END	

	--Add to purchase orders shopping list
	--@AddToBO = 6 is the VB6 integer value for yes
	IF @BackOrder <> 0 And @AddToBO = 6
	BEGIN
				
		SET @AO_Suppliers_ID = 1
				
		SELECT TOP 1 @AO_Suppliers_ID = s.AO_Suppliers_ID
		FROM AP_Products_Suppliers ps
			INNER JOIN AO_Suppliers s
				ON s.AO_Suppliers_ID = ps.AO_Suppliers_ID
		WHERE ps.AP_Products_ID = @ProductID
		AND ps.Slu_AW_Active_ID = 1
		AND s.Slu_AW_Active_ID = 1
		And GETDATE() Between ps.[Start_Date] And '2999-01-01'
				
		SET @RemoteID = 0
				
		SELECT TOP 1 @RemoteID = ISNULL(AW_Remote_Access_ID, 0)
		FROM AW_Remote_Access
		WHERE AW_User_Companies_ID = @CompanyID
		AND Default_Connection = 1

		SELECT @Customer_Name = Surname
		FROM AC_Customers
		WHERE AC_Customers_ID = @CustomerID

		SET @Notes = 'Back Order - ' + @Customer_Name
				
		EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @BackOrder, @Notes, @UserID ,@UserID , @CompanyID, @RemoteID

	END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Order_Candidates]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Order_Candidates]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Candidates
--Purpose       :Returns all Order Candidates
--Functionality :Used in the Purchase Orders UI to filter the records in this query
--              :When an Order Candidate is added to an order that record's show field is set = 0 
--Parameters    :
--Date          :2002/02/19
--Authors       :TB
--Version       :1.0.0
--MODS          :05/09/04 - Added ORDER BY c.Date_Captured DESC
--V6.3	RL	2017/04/08	:Update order candidates to product catalog last cost
---------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

	UPDATE AO_Order_Candidates
	SET AO_Order_Candidates.Last_Cost = p.Last_Cost
	FROM AO_Order_Candidates c
		INNER JOIN AP_Products p
			On c.AP_Products_ID = p.AP_Products_ID

   SELECT
        c.AO_Order_Candidates_ID AS [ID],
        c.Ready AS [Ready],
        c.AP_Products_ID AS [FK ID],
		p.Product_Code AS [Code],
        p.[Description] AS [Product],
        c.AO_Suppliers_ID AS [Supplier ID],
        s.Supplier_Name AS [Supplier],
        c.Order_Date AS [Date],
        c.Qty AS [Qty],
        c.Last_Cost AS [Last Cost],
        c.Notes AS [Notes],
        c.Reviews AS [Reviews],
        ISNULL(u.Firstname + ' ', '') + ISNULL(u.Surname, '') as [Originator],
        c.Date_Captured AS [Date Captured],
        c.[User_ID] AS [User ID],
        c.AW_User_Companies_ID AS [Company]
	FROM AO_Order_Candidates c
        LEFT JOIN AO_Suppliers s
	        ON s.AO_Suppliers_ID = c.AO_Suppliers_ID
        LEFT JOIN AP_Products p
	        ON c.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
	        ON c.Originator =  u.AW_Users_ID
	WHERE c.AW_User_Companies_ID = @CompanyID
    ORDER BY c.Date_Captured DESC 

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Sales_Order_No_CHK]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Sales_Order_No_CHK]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Sales_Order_No_CHK
--Purpose       :Check to see if Sales Order Number already exists in Sales Order basket
--				 or on an open Sales Order document (SYS_AW_Transaction_Types = 16)
--Date          :2017/04/20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Sales_Order_No_CHK]
    (
        @CustomerID int,
        @Customer_Reference	varchar(15),
        @AP_Products_ID	int,
		@Lup_AP_Product_Bins_ID int,
        @Sales_Basket int, --1 Sales basket, 2 Sales Order
       	@CompanyID int,
       	@CHK_Message	varchar(200) OUTPUT,
       	@ExistingTransID	int OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE @Count			int
    
    SET @Count = 0
    SET @CHK_Message = ''
    
    IF @Sales_Basket = 1
    BEGIN
		SELECT @Count = COUNT(*)
		FROM AS_Sales_Order_Details
		WHERE AC_Customers_ID = @CustomerID AND
			Customer_Reference = @Customer_Reference AND
			AP_Products_ID = @AP_Products_ID AND
			AW_User_Companies_ID = @CompanyID AND
			Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

		IF @Count > 0
			SELECT @CHK_Message = 'Sales order number exists in sales basket for THIS PRODUCT.
Item will be added to existing item in the basket.
Do you want to continue?'

		SET @Count = 0

		IF @CHK_Message = ''
		BEGIN
			SELECT @Count = COUNT(*)
			FROM AS_Sales_Order_Details
			WHERE AC_Customers_ID = @CustomerID AND
				Customer_Reference = @Customer_Reference AND
				AW_User_Companies_ID = @CompanyID AND
				Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID
			
			IF @Count > 0
				SELECT @CHK_Message = 'Sales order number exists in sales basket.
Items will be combined with the same order number.
Do you want to continue?'			
		END
	END	
	
	IF @Sales_Basket = 2
	BEGIN
		SET @ExistingTransID = 0

		SELECT @ExistingTransID = AS_Transactions_ID
		FROM AS_Transactions
		WHERE AC_Customers_ID = @CustomerID
		AND Customer_Reference = @Customer_Reference
		AND Slu_AW_Active_ID = 1
		AND AW_User_Companies_ID = @CompanyID
		
		IF @ExistingTransID > 0
			SELECT @CHK_Message = 'An active sales order exists for this customer.
Items will be combined with the existing sales order.
Do you want to continue?'			

	END
SELECT @CHK_Message As '@CHK_Message', @ExistingTransID As '@ExistingTransID'
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Customer_Sales_Order_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Customer_Sales_Order_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Order_Details
--Purpose       :
--Date          :07 JUN 2008
--Authors       :TB
--MODS          :
---------------------------------------------------------------------------------

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

SET NOCOUNT ON

   SELECT 
        s.AS_Sales_Order_Details_ID AS [ID],
        s.AC_Customers_ID AS [CustomerID],
        s.AP_Products_ID AS [ProductID],
        s.[Description] AS [Product],
        s.Product_Code AS [Code],
        s.Customer_Reference As [Order No],
		b.[Description] AS [Bin],
        s.Unit_Price AS [Unit Price],
        s.Quantity AS [Qty],
        s.Back_Order AS [B/O],
        s.Discount_Amount AS [Discount],
        s.Amount AS [Amount],
        s.Shipping_Cost AS [Shipping],
        s.Tax_Amount AS [Tax],
        s.Extended_Amount AS [Total],
        s.Tax_Rate AS [Tax Rate],
        s.Original_Price AS [Orig Price],
        s.Unit_Cost AS [UnitCost],
        s.AP_Promotion_Products_ID AS [PromoProdID],
        s.Promo_Price AS [Promo Price],
        s.Date_Captured AS [Captured],
        s.User_ID AS [UserID],
        s.AW_User_Companies_ID AS [CompanyID],
		s.Lup_AP_Product_Bins_ID AS [Bins_ID]

	FROM AS_Sales_Order_Details s
		INNER JOIN Lup_AP_Product_Bins b
			ON s.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
	WHERE s.AW_User_Companies_ID = @CompanyID AND
          s.AC_Customers_ID = @CustomerID
    ORDER BY s.Date_Captured DESC 

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AC_Suppliers]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AC_Suppliers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create View vw_AC_Suppliers
As

Select 
	ss.AO_Suppliers_ID As 'Supplier ID', 
	IsNull(ss.Supplier_Name,'') As 'Name', 
	IsNull(ss.Supplier_Number,'') As 'Supplier No', 
	IsNull(ss.Old_Code,'') As 'Account No', 
	ISNULL(Convert(Varchar(19),ss.[Start_Date],121),'') As 'Start Date',
	
	--ss.Slu_AW_Active_ID, 
	IsNull(ac.[Description],'') As 'Active',
	Case IsNull(Use_Supplier_Discount_Defaults,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Discount Defaults', 
	--ss.AW_Trade_Discount_Formula_ID, 
	IsNull(td.[Description],'') AS 'Trade Discount',
	--ss.AW_Rebate_Discount_Formula_ID, 
	IsNull(rd.[Description],'') As 'Rebate Discount',
	
	--ss.Use_Other_Discount_Control_Acc, 	
	Case IsNull(Use_Other_Discount_Control_Acc,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Other Discount Account', 
	--ss.AB_Other_Discounts_Account_ID, 
	IsNull(oa.[Description],'') As 'Other Discount Account',
	--ss.Use_Rebate_Discount_Control_Acc, 
	Case IsNull(Use_Rebate_Discount_Control_Acc,0)
		When 0 Then 'No'
		Else 'Yes'
	End As 'Use Rebate Discount Account', 
	--ss.AB_Rebate_Discount_Account_ID, 
	IsNull(oa.[Description],'') As 'Rebate Discount Account',
	
	--ss.Slu_AW_Banks_ID,
	IsNull(sb.[Description],'') As 'Bank', 
	IsNull(Bank_Branch_Code,'') As 'Bank Branch Code', 
	IsNull(ss.Bank_Branch,'') As 'Bank Branch', 
	IsNull(ss.Account_Name,'') As 'Bank Account Name', 
	IsNull(ss.Account_Number,'') As 'Bank Account No', 
	

	IsNull(ss.Credit_Limit,0) As 'Credit Limit', 
	--ss.Slu_AW_Credit_Terms_ID, 
	IsNull(ct.[Description],'') As 'Credit Terms',
	IsNull(ss.Default_Settlement_Discount,0) As 'Default Settlement Disc', 
	IsNull(ss.Supplier_Contact,'') As 'Contact Name', 
	--ss.Sys_AC_Account_Status_ID,
	--ss.Lup_AO_Purchase_Price_Types_ID,
	IsNull(lp.[Description],'') AS 'Purchase Price', 
	--ss.AW_YesNo_Apply_Product_Levy
	IsNull(pl.[Description],'') As 'Apply Product Levy',

	--ss.Sys_AC_Account_Types_ID, 
	IsNull(at.[Description],'') As 'Account Type',
	IsNull(sa.[Description],'') As 'Account Status', 
	--ss.Sys_AW_Tax_Codes_ID, 
	IsNull(tc.[Description],'') As 'Tax Code',
	IsNull(ss.Tax_Number,'') As 'Tax Number', 
	
	--ss.Sys_AO_Delivery_Methods_ID, 
	IsNull(dm.[Description],'') As 'Delivery Method',
	
	--ss.Lup_AO_Supplier_Types_ID,
	IsNull(st.[Description],'') As 'Supplier Type', 
	--ss.Lup_AO_Supplier_Groups_ID,
	IsNull(sg.[Description],'') As 'Supplier Group', 
	
	IsNull(ss.Notes,'') As 'Notes', 

	IsNull(ss.Post_Box,'') As 'Post Box', 
	IsNull(ss.Post_Office,'') As 'Post Office', 
	IsNull(ss.Post_Code,'') As 'Post Code', 

	IsNull(ss.Street_Address,'') As 'Street Address', 
	IsNull(ss.Suburb,'') As 'Suburb', 
	IsNull(ss.City,'') As 'City', 
	IsNull(ss.Street_Post_Code,'') As 'Street Code', 

	--ss.Slu_AW_Countries_ID, 
	IsNull(cc.[Description],'') As 'Country',
	IsNull(ss.Supplier_Telephone,'') As 'Tel No', 
	IsNull(ss.Contact_Cellphone,'') As 'Contact Cell No', 
	IsNull(ss.Supplier_Fax,'') As 'Fax No',  

	IsNull(ss.Web_Site_URL,'') As 'Web Site URL', 
	IsNull(ss.Orders_URL,'') As 'Orders URL', 
	IsNull(ss.Email_Address,'') As 'E-mail Address',
	Convert(Varchar(19),ss.Date_Captured,121) As 'Date Captured'

	--ss.Date_Captured, 
	--ss.User_ID, 
	--ss.AW_User_Companies_ID, 
	--ss.Touched, 
From AO_Suppliers ss
	Left Outer Join Lup_AO_Purchase_Price_Types lp
		On SS.Lup_AO_Purchase_Price_Types_ID = lp.Lup_AO_Purchase_Price_Types_ID
	Left Outer Join AW_Formulas td
		On ss.AW_Trade_Discount_Formula_ID = td.AW_Formulas_ID
	Left Outer Join AW_Formulas rd
		On ss.AW_Rebate_Discount_Formula_ID = rd.AW_Formulas_ID
	Left Outer Join AB_Accounts oa
		On ss.AB_Other_Discounts_Account_ID = oa.AB_Accounts_ID
	Left Outer Join AB_Accounts ra
		On ss.AB_Rebate_Discount_Account_ID = ra.AB_Accounts_ID
	Left Outer Join Slu_AW_Credit_Terms ct
		On ss.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_ID	
	Left Outer Join Sys_AC_Account_Status sa
		On ss.Sys_AC_Account_Status_ID = sa.Sys_AC_Account_Status_ID
	Left Outer Join Sys_AW_Tax_Codes tc
		On ss.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
	Left Outer Join Slu_AW_Countries cc
		On ss.Slu_AW_Countries_ID = cc.Slu_AW_Countries_ID
	Left Outer Join Slu_AW_Banks sb
		On ss.Slu_AW_Banks_ID = sb.Slu_AW_Banks_ID
	Left Outer Join Slu_AW_Active ac
		On ss.Slu_AW_Active_ID = ac.Slu_AW_Active_ID
	Left Outer Join Sys_AO_Delivery_Methods dm
		On ss.Sys_AO_Delivery_Methods_ID = dm.Sys_AO_Delivery_Methods_ID
	Left Outer Join Lup_AO_Supplier_Types st
		On ss.Lup_AO_Supplier_Types_ID = st.Lup_AO_Supplier_Types_ID
	Left Outer Join Lup_AO_Supplier_Groups sg
		On ss.Lup_AO_Supplier_Groups_ID = sg.Lup_AO_Supplier_Groups_ID
	Left Outer Join Sys_AC_Account_Types at
		On ss.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
	Left Outer Join Slu_AW_YesNo pl
		On ss.AW_YesNo_Apply_Product_Levy = pl.Slu_AW_YesNo_ID
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AC_Customers]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AC_Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create View vw_AC_Customers
As

Select 
	c.AC_Customers_ID As 'Customer ID',
	IsNull(c.Surname,'') As 'Surname',
	IsNull(c.Firstnames,'') As 'Firstnames',
	IsNull(c.Initials,'') As 'Initials',
	--c.Slu_AW_Titles_ID,
	ISNULL(t.[Description],'') As 'Title',
	--c.Slu_AW_Languages_ID,
	ISNULL(l.[Description],'') As 'Language',
	IsNull(c.IDReg_Number,'') As 'ID/Reg No',
	ISNULL(Convert(Varchar(19),c.[Start_Date],121),'') As 'Start Date',

	--c.Slu_AW_Active_ID,
	ISNULL(av.[Description],'') As 'Active',
	--AW_YesNo_Change_Doc_Details
	IsNull(pd.[Description],'') As 'Change POS Doc',

	IsNull(c.Customer_Number,'') As 'Customer No',
	--c.AW_YesNo_Net_Billing_ID
	IsNull(nb.[Description],'') As 'Apply Net Billing',
	IsNull(c.Old_Customer_Number,'') As 'Merchant/WHouse No',
	--c.[AW_YesNo_CostPlus_Billing_ID]
	IsNull(nc.[Description],'') As 'Apply Cost+Billing',
	IsNull(c.Head_Office,'') As 'Head Office',

	--c.Lup_AC_Customer_Types_ID,
	ISNULL(ct.[Description],'') As 'Customer Type', 
	--c.Lup_AC_Customer_Groups_ID,
	ISNULL(cg.[Description],'') As 'Customer Group',
	--c.Sys_AC_Use_Assets_ID
	IsNull(ca.[Description],'') As 'Use Assets',
	--c.AW_YesNo_Apply_Product_Levy
	IsNull(al.[Description],'') As 'Apply Product Levy',
	--c.Sys_AW_Tax_Codes_ID, 
	IsNull(tx.[Description],'') As 'Tax Code',
	IsNull(c.Tax_Number,'') As 'V.A.T. Number', 
	--c.AW_YesNo_Purchase_Order_ID
	IsNull(fp.[Description],'') As 'Force Purchase Order No',

	--c.Lup_AC_Discount_Categories_ID,
	IsNull(dc.[Description],'') As 'Sales Discount Catagory',
	--c.Lup_AC_Markup_Categories_ID
	IsNull(mc.[Description],'') As 'Cost+Plus Billing Category',
	ISNULL(c.Credit_Limit,0) As 'Credit Limit',
	--[AW_YesNo_Override_Credit_Limit]
	IsNull(oc.[Description],'') As 'Override Credit Limit',
	--c.Slu_AW_Credit_Terms_ID,
	ISNULL(lc.[Description],'') As 'Credit Terms',
	--[AW_YesNo_Override_Overdue]
	IsNull(oo.[Description],'') As 'Override Overdue',
	--c.Sys_AC_Credit_Term_Types_ID,
	ISNULL(lt.[Description],'') As 'Terms of Sale',
	ISNULL(c.Credit_Insurers_Reference,'') As 'Credit Insurer Ref',
	ISNULL(c.Credit_Insurers_Limit,0) As 'Insurer Credit Limit',
	--c.AW_YesNo_Charge_Interest_ID
	IsNull(ci.[Description],'') As 'Charge Interest',
	IsNull(c.Default_Settlement_Discount,0) As 'Settlement Discount %',

	--Slu_AW_Controllers_ID
	IsNull(cc.Surname,'') + IsNull(cc.FirstName,'') As 'Controller',
	--AW_YesNo_Pre_Notify_ID
	IsNull(pe.[Description],'') As 'Pre-Notify',
	--AW_YesNo_Post_Notify_ID
	IsNull(po.[Description],'') As 'Post-Notify',
	--c.Lup_AS_Reps_ID, 
	ISNULL(cr.[Description],'') As 'Salesperson',
	--c.Lup_AC_Sales_Areas_ID, 
	ISNULL(sa.[Description],'') As 'Sales Area',
	ISNULL(c.Contact_Name,'') As 'Contact Name',
	--Sys_AW_Delivery_Methods_ID
	IsNull(dm.[Description],'') As 'Delivery Method',
	--c.Sys_AC_Account_Types_ID,
	ISNULL(at.[Description],'') As 'Account Type',
	--c.Sys_AC_Account_Status_ID,
	ISNULL(st.[Description],'') As 'Account Status',

	IsNull(c.Notes,'') As 'Notes',

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

	--c.Slu_AW_Countries_ID, 
	ISNULL(cl.[Description],'') As 'Country',
	IsNull(c.Home_Tel_No,'') As 'Home Tel No', 
	IsNull(c.Work_Tel_No,'') As 'Work Tel No', 
	IsNull(c.Cell_No,'') As 'Contact Cell No', 
	IsNull(c.Fax_No,'') As 'Fax No', 

	IsNull(c.Principal_Name,'') As 'Principal Name', 
	IsNull(c.Principal_Firstname,'') As 'Principal Firstname', 
	IsNull(c.Principal_Cell_No,'') As 'Principal Cell No', 
	ISNULL(Convert(Varchar(19),c.Principal_Birthday,121),'') As 'Principal Birthday',

	--Principal_Contact_Method_ID
	IsNull(pc.[Description],'') As 'Principal Delivery Method',

	IsNull(c.Web_Site_URL,'') As 'Web Site URL', 
	IsNull(c.Orders_URL,'') As 'Accounts E-mail', 
	IsNull(c.Home_Email,'') As 'Contact E-mail', 
	IsNull(c.Work_Email,'') As 'Principal E-mail', 
	--AW_YesNo_Send_Email_ID
	IsNull(se.[Description],'') As 'Send E-Mail Message',
	--AW_YesNo_Attach_Tran_ID
	IsNull(ad.[Description],'') As 'Attach Statement Doc',	
	Convert(Varchar(19),c.Date_Captured,121) As 'Date Captured'

From AC_Customers c
	Left Outer Join Slu_AW_Titles t 
		On c.Slu_AW_Titles_ID = t.Slu_AW_Titles_ID
	Left Outer Join Slu_AW_Languages l 
		On c.Slu_AW_Languages_ID = l.Slu_AW_Languages_ID
	Left Outer Join Lup_AC_Customer_Types ct 
		On c.Lup_AC_Customer_Types_ID = ct.Lup_AC_Customer_Types_ID
	Left Outer Join Lup_AC_Customer_Groups cg 
		On c.Lup_AC_Customer_Groups_ID = cg.Lup_AC_Customer_Groups_ID
	Left Outer Join Sys_AC_Account_Status st 
		On c.Sys_AC_Account_Status_ID = st.Sys_AC_Account_Status_ID
	Left Outer Join Sys_AC_Account_Types at 
		On c.Sys_AC_Account_Types_ID = at.Sys_AC_Account_Types_ID
	Left Outer Join Lup_AS_Reps r 
		On c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID
	Left Outer Join Lup_AC_Sales_Areas sa 
		On c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID
	Left Outer Join Slu_AW_Countries cl 
		On c.Slu_AW_Countries_ID = cl.Slu_AW_Countries_ID
	Left Outer Join Sys_AW_Tax_Codes tx 
		On c.Sys_AW_Tax_Codes_ID = tx.Sys_AW_Tax_Codes_ID
	Left Outer Join AW_Users u 
		On c.[User_ID] = u.AW_Users_ID
	Left Outer Join AW_User_Companies cp 
		On c.AW_User_Companies_ID = cp.AW_User_Companies_ID
	Left Outer Join Slu_AW_Active av 
		On c.Slu_AW_Active_ID = av.Slu_AW_Active_ID
	Left Outer Join Sys_AC_Credit_Term_Types lt
		On c.Sys_AC_Credit_Term_Types_ID = lt.Sys_AC_Credit_Term_Types_ID
	Left Outer Join Slu_AW_Credit_Terms lc
		On c.Slu_AW_Credit_Terms_ID = lc.Slu_AW_Credit_Terms_ID
	Left Outer Join Slu_AW_YesNo nb
		On c.AW_YesNo_Net_Billing_ID = nb.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo nc
		On c.AW_YesNo_CostPlus_Billing_ID = nc.Slu_AW_YesNo_ID
	Left Outer Join Sys_AC_Use_Assets ca
		On c.Sys_AC_Use_Assets_ID = ca.Sys_AC_Use_Assets_ID
	Left Outer Join Slu_AW_YesNo al
		On c.AW_YesNo_Apply_Product_Levy = al.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo fp
		On c.AW_YesNo_Purchase_Order_ID = fp.Slu_AW_YesNo_ID
	Left Outer Join Lup_AC_Discount_Categories dc
		On c.Lup_AC_Discount_Categories_ID = dc.Lup_AC_Discount_Categories_ID
	Left Outer Join Lup_AC_Markup_Categories mc
		On c.Lup_AC_Markup_Categories_ID = mc.Lup_AC_Markup_Categories_ID
	Left Outer Join Slu_AW_YesNo oc
		On c.AW_YesNo_Override_Credit_Limit = oc.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo oo
		On c.AW_YesNo_Override_Overdue = oo.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo ci
		On c.AW_YesNo_Charge_Interest_ID = ci.Slu_AW_YesNo_ID
	Left Outer Join Lup_AS_Reps cr
		On c.Lup_AS_Reps_ID = cr.Lup_AS_Reps_ID
	Left Outer Join Slu_AW_YesNo pe
		On c.AW_YesNo_Pre_Notify_ID = pe.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo po
		On c.AW_YesNo_Post_Notify_ID = po.Slu_AW_YesNo_ID
	Left Outer Join Sys_AW_Delivery_Methods dm
		On c.Sys_AW_Delivery_Methods_ID = dm.Sys_AW_Delivery_Methods_ID
	Left Outer Join Sys_AW_Delivery_Methods pc
		On c.Principal_Contact_Method_ID = pc.Sys_AW_Delivery_Methods_ID
	Left Outer Join Slu_AW_YesNo se
		On c.AW_YesNo_Send_Email_ID = se.Slu_AW_YesNo_ID
	Left Outer Join Slu_AW_YesNo pd
		On c.AW_YesNo_Change_Doc_Details = pd.Slu_AW_YesNo_ID
	Left Outer Join AW_Users cc
		On c.Slu_AW_Controllers_ID = cc.AW_Users_ID
	Left Outer Join Slu_AW_YesNo ad
		On c.AW_YesNo_Attach_Tran_ID = ad.Slu_AW_YesNo_ID
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AS_Transaction_Details_Full]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AS_Transaction_Details_Full]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create View vw_AS_Transaction_Details_Full
As

Select 
	th.AS_Transactions_ID As 'Tran Id', 
	th.AC_Customers_ID As 'Customer ID',
	ISNULL(cd.Firstnames, '') + ISNULL(cd.Surname, '') + ISNULL(', ' + cd.Initials, '') AS 'Customer',
	--th.Sys_AW_Transaction_Types_ID	
	IsNull(tt.[Description],'') As 'Transaction Type', 
	IsNull(th.Transaction_Number,'') As 'Transaction No',
	Convert(Varchar(19),th.Transaction_Date,121) As 'Transaction Date',
	IsNull(th.Customer_Reference,'') As 'Ref No', 
	IsNull(th.Comment,'') As 'Comment', 
	 
	IsNull(th.Total_Cost,0) As 'Header Total Cost', 
	IsNull(th.Amount,0) As 'Header Amount', 
	IsNull(th.Total_Tax_Amount,0) As 'Header Tax', 
	IsNull(th.Total_Discount_Amount,0) As 'Header Discount', 
	IsNull(th.Total_Amount,0) As 'Header Total Amount', 
	IsNull(th.Payment_Amount,0) As 'Header Payment Amount',
	--th.Lup_AS_Tills_ID, 
	IsNull(ti.[Description],'') As 'Till',
	--th.Lup_AS_Reps_ID,  
	IsNull(tr.[Description],'') As 'Sales Rep', 	
	Convert(Varchar(19),th.Day_End,121) As 'Day End',		
	Convert(Varchar(19),th.Date_Captured,121) As 'Date Captured',	
	--th.User_ID,
	ISNULL(us.Surname, '') + ISNULL(', ' + us.FirstName, '') AS 'User', 	
	--th.Slu_AW_Active_ID,
	IsNull(ai.[Description],'') As 'Active',
	--th.AW_Comments_ID,	
	IsNull(tc.Comment,'') As 'Transaction Comment', 
	
	--th.AB_Accounts_ID,
	--IsNull(ac.Description,'<None>') As 'GL Account', 
	--th.Expiry_Date, 
	--th.Version_Number, 
	--th.Lup_AS_Marketing_Indicators_ID, 
	--th.Lup_AW_Stores_ID, 
	--th.Lup_AW_Workstations_ID, 
	--th.Lup_AS_Cashiers_ID, 
	--th.Slu_AW_Currencies_ID, 
	--th.Old_Sys_AW_Transaction_Types_ID, 
	--th.Cancelled_User_ID, 
	--th.Cancelled_DateTime, 
	--th.Cashed_Up, 
	--th.Transmitted, 
	--th.AW_User_Companies_ID, 
	--th.Touched, 
	
	IsNull(pr.Product_Code,'') As 'Product Code',
	IsNull(pr.[Description],'') As 'Product Description',
	--td.Lup_AP_Product_Bins_ID,
	IsNull(pb.[Description],'') As 'Product Bin',
	IsNull(td.Quantity,0) As 'Detail Qty', 
	IsNull(td.Unit_Cost,0) As 'Detail Cost', 
	IsNull(td.Unit_Price,0) As 'Detail Unit Price', 
	IsNull(td.Original_Price,0) As 'Detail Original Price', 
	IsNull(td.Original_Discount,0) As 'Detail Original Discount', 
	IsNull(td.Discount_Amount,0) As 'Detail Discount', 
	IsNull(td.Tax_Amount,0) As 'Detail Tax', 
	IsNull(td.Extended_Amount,0) As 'Detail Total Amount',
	--td.Slu_AW_Active_ID,
	IsNull(da.[Description],'') As 'Detail Active',
	--td.AS_Job_References_ID,  
	IsNull(af.Job_No,'') As 'Job Ticket',
	IsNull(td.Serial_No,'') As 'Serial No', 
	IsNull(td.Make,'') As 'Make', 
	IsNull(td.Customer,'') As 'Job Customer', 
	IsNull(td.TDHeader,'') As 'Detail Header', 
	IsNull(td.TDDetail,'') As 'Detail Detail' 

	--td.AS_Transaction_Details_ID, 
	--td.AS_Transactions_ID, 
	--td.AP_Products_ID,
	--td.Commission_Amount, 
	--td.AP_Promotion_Products_ID, 
	--td.Date_Captured, 
	--td.User_ID, 
	--td.AW_User_Companies_ID, 
	--td.Touched, 
	--td.Back_Order, 
	--td.Consignment_Left, 
From AS_Transactions th
	Left Outer Join AS_Transaction_Details td
		On th.AS_Transactions_ID = td.AS_Transactions_ID
	Left Outer Join AC_Customers cd
		On th.AC_Customers_ID = cd.AC_Customers_ID
	Left Outer Join AW_Comments tc
		On th.AW_Comments_ID = tc.AW_Comments_ID
	Left Outer Join Sys_AW_Transaction_Types tt
		On th.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
	Left Outer Join Lup_AS_Tills ti
		On th.Lup_AS_Tills_ID = ti.Lup_AS_Tills_ID
	Left Outer Join Lup_AS_Reps tr
		On th.Lup_AS_Reps_ID = tr.Lup_AS_Reps_ID
	Left Outer Join AW_Users us
		On th.[User_ID] = us.AW_Users_ID
	Left Outer Join Slu_AW_Active ai
		On th.Slu_AW_Active_ID = ai.Slu_AW_Active_ID
	Left Outer Join AP_Products pr
		On td.AP_Products_ID = pr.AP_Products_ID
	Left Outer Join AF_Job_Tickets af
		On td.AS_Job_References_ID = af.AF_Job_Tickets_ID
	Left Outer Join Lup_AP_Product_Bins pb
		On td.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
	Left Outer Join Slu_AW_Active da
		On td.Slu_AW_Active_ID = da.Slu_AW_Active_ID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_RPT_Sales_Order_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_RPT_Sales_Order_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Sales_Order_Print
--Purpose       :POS Sales Order printing
--Parameters    :
--Date          :2008/06/12
--Authors       :TB
--MODS:         :
--V6.3	RL	2017/04/21	:Added Back Order Qty
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    DECLARE @TextMessage varchar(100),
            @TextMessagePrint varchar(100),
            @Message varchar(100),
            @WhichAddress tinyint,
            @WhichName tinyint,
            @PaymentMethod varchar(20),
            @AddressOption0 varchar(20),
            @AddressOption1 varchar(20)


    SET @WhichAddress = 0
    SET @Message = ''


    SELECT TOP 1 @TextMessage = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'



    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 @TextMessagePrint = ISNULL(Control_Value, '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    IF @TextMessagePrint = '1'
        BEGIN
            SET @Message = @TextMessage
        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 TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''), 20)
	FROM AS_Transactions_Transactions att
        LEFT JOIN AS_Transaction_Payments tp
            ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID
        LEFT JOIN Sys_AW_Payment_Methods pm
            ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID
	WHERE att.Source_AS_Transactions_ID = @TransactionID
    ORDER BY att.Source_AS_Transactions_ID


	SELECT 
		RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [CustomerName],
        ISNULL(c.Firstnames, '') AS [TradeName],
        ISNULL(c.Contact_Name, '') AS [Contact],

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

		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],
-------------------------------------------------------------------------------
		p.Product_Code AS [ProductCode],
		p.Description AS [ProductDescription],
		(td.Quantity + td.Back_Order) AS [DetailQty],
		td.Unit_Price AS [DetailUnitPrice],

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

		td.Discount_Amount AS [DetailDiscount],
       (td.Unit_Price * (td.Quantity + td.Back_Order)) + td.Discount_Amount AS [DetailAmount],
		td.Tax_Amount AS [DetailTaxAmount],
		td.Extended_Amount AS [DetailExtendedAmount],
        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.Comment AS [Comment],

        ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Cell_No)), '') +
        ISNULL(' / ' + RTRIM(LTRIM(c.Home_Tel_No)), '') AS [TelNos],
        ISNULL('Fax No ' + RTRIM(LTRIM(c.Fax_No)), '') AS [FaxNo],

        ISNULL(RTRIM(LTRIM(c.Tax_Number)), '') AS [VATNo],

        CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> ''
             THEN 'Jobcard No: ' + RTRIM(LTRIM(ts.Transaction_Numbers))
             ELSE ''
             END AS [JobSource],

        t.AW_User_Companies_ID AS [CompanyID],
        ROUND(ISNULL((td.Quantity + td.Back_Order), 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass],
        ROUND(ISNULL((td.Quantity + td.Back_Order), 0) * ISNULL(p.Pack_Volume, 0), 2) AS [PackVolume],
        @PaymentMethod AS [PayMethod],

        CASE WHEN td.AS_Job_References_ID = 0 
             THEN NULL
             ELSE td.AS_Job_References_ID
             END AS [JobRefNo],

        @Message AS [TextMessage],
        @WhichAddress AS [AddressType],
        td.Serial_No AS [SerialNo],
        td.Make AS [Make],
        td.Customer AS [Customer],
        @WhichName AS [NameType]

	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_Details td
            ON t.AS_Transactions_ID = td.AS_Transactions_ID
        LEFT JOIN AP_Products p
            ON td.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AW_Users u
            ON t.[User_ID] = u.AW_Users_ID
        LEFT JOIN AS_Transaction_Sources ts
            ON t.AS_Transactions_ID = ts.AS_Transactions_ID
        LEFT JOIN AW_Comments com
            ON t.AW_Comments_ID = com.AW_Comments_ID
	WHERE t.AS_Transactions_ID = @TransactionID
    ORDER BY AS_Transaction_Details_ID



SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Insert_OR_Update_GRV_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Insert_OR_Update_GRV_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_GRV_Detail
--Purpose       :Inserts GRV Detail and Updates Inventory Last_Cost, On_Hand, and
--              :        REVAL/DEVAL Stock Adjustment in sp_AP_Update_Inventory_Details
--Functionality :
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--Version       :1.0.0
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Fixed this: On_Hand was only updated
--                              if @Prev_Last_Cost <> @New_Last_Cost
--              :21/05/02 - Moved the Reval/Deval Adjustment to
--              :               sp_AP_Update_Inventory_Details
--              :04/06/02 - Added text to @Note before sp_AP_Update_Inventory_Details
--              :               is called
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :           and renamed @Current* variables to @Prev*
--              :18/10/03 - Added @GRV_ID as new input parameter to
--              :           sp_AP_Update_Inventory_Details get the GRV
--              :           Delivery_Note_Number as GLTran RefNo
--              :19/10/03 - Added ROUND(@New_Last_Cost, 2)
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.5.8	RL	:2013-02-04 - Changed AO_Order_Details.Received_Qty From Decimal(9,3) to Decimal(19,3)
--							Tirepoint uses the GRVs to invoice out the KM traveled on there call outs 
--V6.2	RL		:2015-04-16	- Returned AO_GRV_Details_ID to be used for Consignment stock tracking
--V6.2	RL		:2015-04-16	:Added @AO_GRV_ID_Consignment parameter for linking Consignment GRV
--V6.2	RL		:2015-12-01	:Product Bin qty changes
--V6.3	RL		:2017-04-21 :Added check to fill back orders
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_OR_Update_GRV_Detail]
    (	
    	@AO_Order_Details_ID int = 0,
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(9,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,
    	@AO_GRV_Details_ID_Consignment varchar(20),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

	DECLARE @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),
            @New_Last_Cost money,
            @New_On_Hand Decimal(9,3),
    		@Orders_ID Int,
    		@Received_Qty Decimal(19,3),
    		@Count1 int,
    		@Count2 int,
    		@Net_Purchase_Price money,
    		@Note varchar(70),
    		@User_Name varchar(40),
        --> GL variables for Supplier GL Detail
    		@Use_Rebate_Disc_GL_Acc Bit,
    		@Use_Other_Disc_GL_Acc Bit,
    		@Rebate_Disc_GL_Acc int,
    		@Other_Disc_GL_Acc int,
    		@Purchases_Contol_Acc_ID int,
    		@Suppliers_ID int,
    		@AO_GRV_Details_ID int,
            @ConsignmentStock    decimal(9,3),
    		@IsConsignment	int,
    		
			@ProductsQty				decimal(9,3),			
			@ProductConsignmentStockQty		decimal(9,3),
			@chkSOAutoReplenishBO_GRV	varchar(10)

    BEGIN
    	BEGIN
    		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,
        			AO_GRV_Details_ID_Consignment
                )
    		VALUES
                (
                    @AO_GRV_ID ,
        			@AP_Products_ID ,
        			@Qty ,
        			@Unit_Last_Cost ,
        			@TradeDisc ,
        			@RebateDisc ,
        			@OtherDisc ,
        			@NetAmount ,
        			@Tax_Code_ID ,
        			@TaxAmount ,
        			@TotalCost ,
        			@UserID ,
        			@CompanyID,
        			@AO_GRV_Details_ID_Consignment
                )
    	END
    	    	
    	SELECT @AO_GRV_Details_ID = SCOPE_IDENTITY() 
    	
    	BEGIN	
            SELECT @Prev_On_Hand = ISNULL(On_Hand, 0) ,
                   @Prev_Last_Cost = ISNULL(Last_Cost, 0) ,
                   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0) ,
                   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0) ,
                   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0)
    		FROM AP_Products
    		WHERE AP_Products_ID = @AP_Products_ID

    		--RL V6.2 2016-05-01 Consignment stock must not be added to average cost calculation
    		--Consignment stock is not GRV'd stock
    		--SET @ConsignmentStock = ISNULL(dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID),0)
			--SET @Prev_On_Hand = @Prev_On_Hand - @ConsignmentStock

--Insert Into Temp_Debug Values('32 - @Prev_On_Hand',Convert(Varchar(100),@Prev_On_Hand)) 
--Insert Into Temp_Debug Values('32 - @Prev_Last_Cost',Convert(Varchar(100),@Prev_Last_Cost)) 

--SELECT @ProductConsignmentStockQty = dbo.fn_AP_Get_Consignment_Stock_Qty(@AP_Products_ID)
--Insert Into Temp_Debug Values('(32 Begin)28 - @ProductConsignmentStockQty',Convert(Varchar(100),@ProductConsignmentStockQty))   	

--Select @ProductsQty = On_hand
--From AP_Products 
--Where AP_Products_ID = @AP_Products_ID
--Insert Into Temp_Debug Values('(32 Begin)28 - @ProductsQty',Convert(Varchar(100),@ProductsQty))   	

  
    		SET @New_On_Hand = @Prev_On_Hand + @Qty    --New On_Hand Qty
    		
--Insert Into Temp_Debug Values('32 @New_On_Hand',Convert(Varchar(100),@New_On_Hand))
            
    		BEGIN
    			SELECT @Suppliers_ID = AO_Suppliers_ID
    			FROM AO_GRV
    			WHERE AO_GRV_ID = @AO_GRV_ID
    		
    			SELECT  @Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    					@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    					@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    					@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    			FROM AO_Suppliers 
    			WHERE AO_Suppliers_ID = @Suppliers_ID
    	
    			SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    			FROM AB_Control_Accounts
    			WHERE Control_Number = 301    --Purchases
    		END

--> CALCULATE NEW LAST COST ----------------------------------------------

--Insert Into Temp_Debug Values('32 - @Qty',Convert(Varchar(100),ISNULL(@Qty,0)))

            SET @Net_Purchase_Price = ISNULL(@Unit_Last_Cost, 0) * ISNULL(@Qty, 1)

        --> Update Purchase with Net Acquisition Cost
            IF @Use_Rebate_Disc_GL_Acc = 1    -- 1 = YES
				BEGIN
					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
                        --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
                        SET @Net_Purchase_Price = @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
					ELSE
                        --> Last_Cost = UnitPrice - (Trade)
                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@TradeDisc, 0)
				END

        --> @Use_Rebate_Disc_GL_Acc = 0    -- 0 = NO
			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
                SET @Net_Purchase_Price =  @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
    
			IF @Use_Other_Disc_GL_Acc = 1    -- 1 = YES
				BEGIN
					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)
				END

        --> @Use_Other_Disc_GL_Acc = 0    -- 0 = NO
			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate + Other) = Net Acquisition Cost
				SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)

------------------------------------------------------------------------
        --> New Last_Cost
            SET @New_Last_Cost = ROUND(@Net_Purchase_Price / ISNULL(@Qty, 1), 2)
------------------------------------------------------------------------
        --> Updates Last_Cost & Inventory Adjustment for Reval/Deval

            SET @Note = 'Goods Received by '
--Insert Into Temp_Debug Values('Cons ID ',Convert(Varchar(100),ISNULL(@AO_GRV_Details_ID_Consignment,0)))

			SET @IsConsignment = 0
			IF EXISTS
			(
				SELECT 1
				FROM AO_GRV
				WHERE AO_GRV_ID = @AO_GRV_ID
				AND SYS_AW_Transaction_Types_ID in (31,32,33,34,35)
			)
			BEGIN
				SET @IsConsignment = 1
			END
--Insert Into Temp_Debug Values('32 @IsConsignment',Convert(Varchar(100),ISNULL(@IsConsignment,0)))			
--Insert Into Temp_Debug Values('32 @New_Last_Cost',Convert(Varchar(100),ISNULL(@New_Last_Cost,0)))			
--Insert Into Temp_Debug Values('32 @New_On_Hand',Convert(Varchar(100),ISNULL(@New_On_Hand,0)))			
			IF @IsConsignment = 1
			BEGIN
				SET @Note = 'Consignment Returned - No Affect On Average Cost!!!!'
			END
			
			EXEC sp_AP_Update_Inventory_Details
                    @AO_GRV_ID,
                    @AP_Products_ID,
					@New_Last_Cost,
					@New_On_Hand,
					@Prev_Job_Reserved,
					@Prev_Sales_Order_Reserved,
					@Prev_Quote_Reserved,
					@Note,
					@UserID ,
					@CompanyID
------------------------------------------------------------------------

    	END
    	
    	IF @AO_Order_Details_ID <> 0 
    		BEGIN
    
    			SELECT @Received_Qty = ISNULL(Received_Qty,0),
    				@Orders_ID = AO_Orders_ID	
    			FROM AO_Order_Details 
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    			
    			SET @Received_Qty =  @Received_Qty + @Qty			 
    		
    			UPDATE AO_Order_Details
    			SET Receipt_Date = GetDate(),
    				Received_Qty = @Received_Qty
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    
            --> CERTIFY ORDER as COMPLETE if items received in full
    			SELECT @Count1 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE AO_Orders_ID = @Orders_ID
    			
    			SELECT @Count2 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE Received_Qty  >= (Order_Qty + Back_Order_Qty) AND
                      AO_Orders_ID = @Orders_ID
    			
    			IF @Count2 = @Count1
    				BEGIN
    					UPDATE AO_Orders
    					SET Complete = 1 
    					WHERE AO_Orders_ID = @Orders_ID 
    				END
    		END	

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

--Select @chkSOAutoReplenishBO_GRV As '@chkSOAutoReplenishBO_GRV'	
	
		IF @chkSOAutoReplenishBO_GRV = '1'
		BEGIN	
    		--V6.3 RL 2017/04/21 Check if sales orders have back orders	
    		EXEC sp_AO_Update_Sales_Orders @AO_GRV_ID, @AP_Products_ID, @New_On_Hand, @CompanyID	
    	END
			
    	RETURN @AO_GRV_Details_ID			
    END

SET NOCOUNT OFF
GO

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_Search_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Search_Detail
--Purpose       :Selects POS Transaction Detail Shaped
--Date          :2003/12/18
--Authors       :TB
--MODS          :
--2004.5.3      :29/08/11 - Added [Promotion Sale], [Job No], [Serial No], [Make] fields
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Transaction_Search_Detail] 
    (
        @TransactionID int
    )
AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                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))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity)) * 100))
                ELSE 0.00
                END AS [Std GP%],
           (d.Quantity + d.Back_Order) AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,(d.Quantity * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Disc],
           d.Original_Price AS [Orig Price],
           pp.[Description] AS [Promotion Sale], 
           d.AS_Job_References_ID AS [Job No],
           d.Serial_No AS [Serial No],
           d.Make AS [Make]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AP_Products pp
            ON d.AP_Promotion_Products_ID = pp.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Transaction_History_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Transaction_History_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_History_Detail
--Purpose       :Selects Customer Transaction Detail Shaped
--Date          :2004/12/06
--Authors       :TB
--MODS          :
--2004.5.3      :29/08/11 - Added [Promotion Sale], [Job No], [Serial No], [Make] fields
--V6.3	RL	2017/04/21	:Added Back Order Qty to Qty For Sales Orders
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID], 
           p.[Description] AS [Product], 
           p.Product_Code AS [Code], 
           CONVERT(money,(d.Extended_Amount - d.Tax_Amount) - ((d.Quantity + d.Back_Order) * d.Unit_Cost)) AS [GP],
           CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, (d.Quantity + d.Back_Order), d.Unit_Cost) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount)) * 100))
                ELSE 0.00
                END AS [Act GP%],
           CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, (d.Quantity + d.Back_Order)) <> 0
                THEN CONVERT(money, ((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, (d.Quantity + d.Back_Order)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, (d.Quantity + d.Back_Order))) * 100))
                ELSE 0.00
                END AS [Std GP%],
           (d.Quantity + d.Back_Order) AS [Qty],
           d.Unit_Price AS [Unit Price], 
           d.Discount_Amount AS [Sales Disc],
           d.Tax_Amount AS [VAT],
           d.Extended_Amount AS [Amount],
           d.Unit_Cost AS [Unit Cost], 
           CONVERT(money,((d.Quantity + d.Back_Order) * d.Unit_Cost)) AS [Total Cost],
           CONVERT(money,(d.Unit_Price - d.Original_Price) * (d.Quantity + d.Back_Order)) AS [Price Disc],
           d.Original_Price AS [Orig Price],
           pp.[Description] AS [Promotion Sale], 
           d.AS_Job_References_ID AS [Job No],
           d.Serial_No AS [Serial No],
           d.Make AS [Make]
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
        LEFT JOIN AP_Products pp
            ON d.AP_Promotion_Products_ID = pp.AP_Products_ID
    WHERE d.AS_Transactions_ID = @TransactionID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Sales_Order_Header]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Sales_Order_Header]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Sales_Order_Header
--Purpose       :Selects Customer Sales Orders Header Shaped
--Date          :2008/06/17
--Authors       :TB
--MODS          :
--2004.3.9      :06/07/08 - Added LEFT JOIN of AS_Transactions_Xref* tables to show
--              :           REVERSE SOURCE Invoice/Refund the Sales Order was charged
--              :           out on if it exists. Returns NULL is not exists
--V6.3	RL	2017-05-03	:Added Active Description
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Shape_Sales_Order_Header]
	(
        @CustomerID int,
        @TransactionTypeID int,
        @StartDate datetime,
        @EndDate datetime,
        @Option tinyint = 0
	)

AS

SET NOCOUNT ON


    IF @Option = 0        --> All Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                CASE WHEN ai.[Description] IS NULL
                     THEN 'Recall XREF'
                     ELSE ai.[Description]
                END AS [Active]
                
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END
    ELSE
    IF @Option = 1        --> Uninvoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 2        --> Invoiced Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID = 0 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END

    ELSE
    IF @Option = 3        --> Cancelled Sales Orders
        BEGIN
            SELECT
                h.AS_Transactions_ID AS [ID],
                h.AC_Customers_ID AS [CustomerID],
                t.[Description] AS [Type],
                h.Transaction_Date AS [Date],
                h.Customer_Reference AS [Cust Ref],
                h.Transaction_Number AS [S/O No],
                h.Amount AS [Amount],
                h.Total_Discount_Amount AS [Discount],
                h.Total_Tax_Amount AS [Tax],
                h.Total_Amount AS [Total],
                h.Payment_Amount AS [Payment],
                ISNULL(h.Transaction_Number, '') AS [Doc No],
                ISNULL(h.Total_Amount, 0) AS [Doc Total],
                h.Comment AS [Comment],
                u.UserName AS [User],
                h.Slu_AW_Active_ID AS [Active],
                t.Sys_AW_Transaction_Types_ID AS [TypeID],
                ai.Description As [Active]
            FROM AS_Transactions h
                INNER JOIN Sys_AW_Transaction_Types t
                    ON h.Sys_AW_Transaction_Types_ID = t.Sys_AW_Transaction_Types_ID
                INNER JOIN AW_Users u
                    ON h.User_ID = u.AW_Users_ID
                --LEFT JOIN AS_Transactions_Xref_Sources xd
                --    ON h.AS_Transactions_ID = xd.AS_Transactions_ID
                --LEFT JOIN AS_Transactions_Xref xh
                --    ON xd.AS_Transactions_Xref_ID = xh.AS_Transactions_Xref_ID
                --LEFT JOIN AS_Transactions ch
                --    ON xh.AS_Transactions_ID = ch.AS_Transactions_ID
                LEFT JOIN Slu_AW_Active ai
					On ai.Slu_AW_Active_ID = h.Slu_AW_Active_ID                    
            WHERE h.AC_Customers_ID = @CustomerID AND
                  h.Sys_AW_Transaction_Types_ID = @TransactionTypeID AND
                  h.Slu_AW_Active_ID > 1 AND
                 (DATEDIFF(d, h.Transaction_Date, @StartDate) <= 0 AND
                  DATEDIFF(d, h.Transaction_Date, @EndDate) >= 0)
            ORDER BY h.Transaction_Date DESC
        END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Reserved_Stock]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Reserved_Stock]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------
--Description   :sp_AP_Select_Reserved_Stock
--Purpose       :Fetches RESERVED for ONE ProductID in POS
--Date          :2009/06/04
--Authors       :TB
--MODS          :
--V6.3		RL	:2017-05-04 - Added Sales Order reserved amounts to Job Card reserved amounts
---------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Reserved_Stock]
	(
        @CompanyID int,
    	@ProductID int
	)

AS

SET NOCOUNT ON


    SELECT  h.AW_User_Companies_ID AS [CompanyID],
            h.Sys_AW_Transaction_Types_ID AS [TranTypeID],
            h.AS_Transactions_ID AS [TranID],
            tt.[Description] AS [Type],
            ISNULL(c.Surname, '') + ISNULL(' ' + c.Firstnames, '')
            + ' (' + CONVERT(varchar(10), c.AC_Customers_ID) + ')' AS [Customer],
            (d.Quantity + d.Back_Order) AS [Qty],
            d.Unit_Price AS [Unit Price],
            h.Transaction_Number AS [No],
            h.Transaction_Date AS [Date],
            ISNULL(h.Customer_Reference,'') AS [Order],
            ISNULL(h.Comment, '') AS [Comment],
            ISNULL(u.UserName, '') AS [User]
    FROM AS_Transactions h
         INNER JOIN AS_Transaction_Details d
             ON h.AS_Transactions_ID = d.AS_Transactions_ID
         INNER JOIN AC_Customers c
             ON c.AC_Customers_ID = h.AC_Customers_ID
         INNER JOIN Sys_AW_Transaction_Types tt
             ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
         INNER JOIN AW_Users u
             ON h.Lup_AS_Cashiers_ID = u.AW_Users_ID
    WHERE h.AW_User_Companies_ID = @CompanyID AND
          h.Slu_AW_Active_ID = 1 AND
          d.AP_Products_ID = @ProductID AND
         (h.Sys_AW_Transaction_Types_ID = 2 OR
          h.Sys_AW_Transaction_Types_ID = 16)
    ORDER BY [CompanyID], [TranTypeID], [Date]

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Order_Details_Product_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Order_Details_Product_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Details_Product_Details
--Purpose       :Gets the details for a product that is selected in the
--              :    Order Details section for editing 
--				:    of the Purchase Orders UI
--Functionality :
--Parameters    :
--Date          :2002/02/09
--Authors       :TB
--MODS          :
--2004.2.5      :14/01/06 - Replaced in DECLARE all amount type DECIMAL(14,6) variable
--              :           declarations with type MONEY !!!!
--V6.3	RL	2017/05/04	:Change select reserved stock from transactions and not AP_Products
-----------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Order_Details_Product_Details]
    (
        @AP_Products_ID int,
    	@Suppliers_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Use_Supplier_Discounts Bit,
    	@Use_Rebate_Disc_GL_Acc Bit,
    	@Use_Other_Disc_GL_Acc Bit,
    	@Rebate_Disc_GL_Acc int,
    	@Other_Disc_GL_Acc int,
    	@Purchases_Contol_Acc_ID int,

    	@OtherDisc money,
    	@RebateDisc money,
    	@TradeDisc money,
    	@OtherDiff money,
    	@RebateDiff money,
    	@TradeDiff money,
    	@GrossPurchasePrice money,
    	@Last_Cost money

    -- 	SET @AP_Products_ID = 1
    -- 	SET @Suppliers_ID = 4 
    -- 	SET @Company_ID = 1
    
    BEGIN 
    	BEGIN
    		SELECT @Use_Supplier_Discounts = Use_Supplier_Discount_Defaults,
    				@Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    				@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    				@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    				@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    		FROM AO_Suppliers 
    		WHERE AO_Suppliers_ID = @Suppliers_ID
    
    		SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    		FROM AB_Control_Accounts
    		WHERE Control_Number = 301
    
    	END
    
        ---------------------------------------------------------------------
        --    Calculate the Last Trade, Rebate and Other Discounts allowed
        --        for the @AP_Products_ID product
        --    To be used in a reverse Calculation of the Gross Purchase Price
        --        for the @AP_Products_ID product
        ---------------------------------------------------------------------
    
    	BEGIN
    		BEGIN
    			SELECT @Last_Cost = ISNULL(Last_Cost,0)
    			FROM AP_Products 
    			WHERE AP_Products_ID = @AP_Products_ID
    		END 
    
    		BEGIN	
    			SET @OtherDisc = 0
    			SET @RebateDisc = 0
    			SET @TradeDisc = 0
    
    			SELECT TOP 1 @OtherDisc =ISNULL(Other_Discount_Percentage,0) ,
                             @RebateDisc = ISNULL(Rebate_Discount_Percentage,0) ,
                             @TradeDisc = ISNULL(Trade_Discount_Percentage,0) 
    			FROM AO_Order_Details
    			WHERE AP_Products_ID = @AP_Products_ID AND
    				  AW_User_Companies_ID = @Company_ID AND
    				  Receipt_Date IS NOT NULL
    			ORDER BY Receipt_Date DESC
    		END
    
    		BEGIN			
    			SET @OtherDiff = ((100 - @OtherDisc)/100) 
    			SET @RebateDiff = ((100 - @RebateDisc)/100) 
    			SET @TradeDiff = ((100 - @TradeDisc)/100)	
    
    ---------------------------------------------------------------------------------------------------------------			
    		/* Determine if the Other Discount was subtracted from Unit Price to Calculate Last Cost */
    
    			IF @Use_Other_Disc_GL_Acc = 1
    				BEGIN
    					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID
    						BEGIN
    							SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    						END
    					ELSE
    						BEGIN
    							SET @GrossPurchasePrice = @Last_Cost
    						END
    
    				END
    			ELSE
    			/* This means that the Other Disc was written to the Purchases Control Acc*/
    				BEGIN
    					SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    				END
    
    ---------------------------------------------------------------------------------------------------------------					
    		/* Determine if the Rebate Discount was subtracted from Unit Price to Calculate Last Cost */
    
    			IF @Use_Rebate_Disc_GL_Acc = 1
    				BEGIN
    					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID
    						BEGIN
    							SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    						END
    					ELSE
    						BEGIN
    							SET @GrossPurchasePrice = @GrossPurchasePrice 
    						END
    
    				END
    			ELSE
    			/* This means that the Other Disc was written to the Purchases Control Acc*/
    				BEGIN
    					SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    				END
    
    ---------------------------------------------------------------------------------------------------------------					
    
    -- 			SET @GrossPurchasePrice = (@Last_Cost / @OtherDiff)
    -- 			SET @GrossPurchasePrice = (@GrossPurchasePrice / @RebateDiff)
    -- 			SET @GrossPurchasePrice = (@Last_Cost / @RebateDiff)
    
    ---------------------------------------------------------------------------------------------------------------					
    
    			SET @GrossPurchasePrice = (@GrossPurchasePrice / @TradeDiff)
    		END
    
    	END
    ---------------------------------------------------------------------------------------------------------------
    
    		SELECT DISTINCT P.AP_Products_ID AS [ID],
    			P.[Description] AS [Product],
    			dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) as [Price 1],
    			dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()) as [Price 2],
    -- 			P.Price1_Price1 AS [Price 1],
    -- 			P.Price1_Price2 AS [Price 2],
    			@GrossPurchasePrice AS [Gross_Purchase_Price],
    			(SELECT DISTINCT Lead_Time 
    				FROM AP_Products_Suppliers 
    				WHERE AP_Products_ID = @AP_Products_ID AND AO_Suppliers_ID = @Suppliers_ID) 
    				AS [Lead Time],
    			P.Service_Level AS [Service Level],
    			P.Last_Sale_Date AS [Last Sale],
    			P.On_Hand AS [Stock On Hand],
    			--V6.3 Get reserved stock from transactions and not product table
    			CONVERT(decimal(9, 3), (dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID) + dbo.fn_AP_Products_Sales_Order_Reserved(p.AP_Products_ID)) ) as [Stock Reserved],
    			--P.Job_Reserved + P.Sales_Order_Reserved AS [Stock Reserved],
    			P.Last_Cost	AS [Last_Cost],	
    
    -- 			(SELECT Sum(OD.Order_Qty)+ Sum(OD.Back_Order_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 OD.AP_Products_ID = @AP_Products_ID ) 
    -- 					AS [Qty on order],
    		
    			(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 = @AP_Products_ID) AS [Qty on order],
    
    
    			(SELECT Sum(OD.Order_Qty)+ Sum(OD.Back_Order_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 null AND OD.AP_Products_ID = @AP_Products_ID ) 
    					AS [Orders Pending],
    		
    			(SELECT Sum(OC.Qty) 
    					FROM AO_Order_Candidates OC 
    					WHERE OC.AP_Products_ID =  @AP_Products_ID ) 
    					AS [Shopping List Qty],

            --> SELECT THE DISCOUNT FORMULAS OF THE SUPPLIER/PRODUCT
                CASE @Use_Supplier_Discounts WHEN 1
                    THEN 
                        (SELECT AW_Trade_Discount_Formula_ID
                         FROM AO_Suppliers
                         WHERE AO_Suppliers_ID = @Suppliers_ID)
    				ELSE
    					(SELECT DISTINCT AW_Trade_Discount_Formula_ID
                         FROM AP_Products_Suppliers
                         WHERE AP_Products_ID = @AP_Products_ID AND
                               AO_Suppliers_ID = @Suppliers_ID AND
                               AW_User_Companies_ID = @Company_ID)
    				END	AS [Trade_Discount_Formula_ID],
    			
                CASE @Use_Supplier_Discounts WHEN 1
                    THEN
                        (SELECT AW_Rebate_Discount_Formula_ID
                         FROM AO_Suppliers
                         WHERE AO_Suppliers_ID = @Suppliers_ID)
    				ELSE   
                        (SELECT DISTINCT AW_Rebate_Discount_Formula_ID
                         FROM AP_Products_Suppliers
                         WHERE AP_Products_ID = @AP_Products_ID AND
                               AO_Suppliers_ID = @Suppliers_ID AND
                               AW_User_Companies_ID = @Company_ID)
    				END AS [Rebate_Discount_Formula_ID],
    			
                (SELECT Sys_AW_Tax_Codes_ID FROM AO_Suppliers WHERE AO_Suppliers_ID = @Suppliers_ID) AS [Tax_Codes_ID]
    			
    		FROM AP_Products P 
    		WHERE P.AP_Products_ID = @AP_Products_ID 
    
    END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Account_Is_TB_Control]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Account_Is_TB_Control]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Account_Is_TB_Control
--Purpose       :VALIDATE IF GL Account is a trade debtor control account
--Date          :2017-05-15
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Account_Is_TB_Control]
    (
        @GLAccountID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

	SET @Exists = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE Control_Number in (101, 105)
		AND AB_Accounts_ID = @GLAccountID
	)
	BEGIN
		SET @Exists = 1
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Account_Is_TC_Control]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Account_Is_TC_Control]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Account_Is_TC_Control
--Purpose       :VALIDATE IF GL Account is a trade creditor control account
--Date          :2017-05-15
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Account_Is_TC_Control]
    (
        @GLAccountID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

	SET @Exists = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AB_Control_Accounts
		WHERE Control_Number in (201, 207)
		AND AB_Accounts_ID = @GLAccountID
	)
	BEGIN
		SET @Exists = 1
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Sales_Order_Filled_CHK]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Sales_Order_Filled_CHK]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AO_Sales_Order_Filled_CHK
--Purpose       :Check if GRV will replinish Sales Order Back Order
--Returns       :
--Date          :2017-05-16
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Sales_Order_Filled_CHK]
	(
		@AP_ProductsID int,
		@Qty decimal(9,3),
        @CompanyID int,
		@Sales_Order_Filled tinyint OUTPUT
	)
AS

	SET @Sales_Order_Filled = 0
	
	IF EXISTS
	(
		SELECT 1
		FROM AS_Transactions h
			INNER JOIN AS_Transaction_Details d
				ON h.AS_Transactions_ID = d.AS_Transactions_ID
		WHERE d.AP_Products_ID = @AP_ProductsID
		AND h.AW_User_Companies_ID = @CompanyID
		AND h.Slu_AW_Active_ID = 1
		AND d.Back_Order <> 0
		AND h.Sys_AW_Transaction_Types_ID = 16
	)
	BEGIN
		SET @Sales_Order_Filled = 1
	END
GO

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

-------------------------------------------------------------------------------
--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),
			
			@Today							DateTime,
    		@M1								Tinyint,
    		@Y1								Int,
    		@M2								Tinyint,
    		@Y2								Int,
    		@M3								Tinyint,
    		@Y3								Int,
    		@M4								Tinyint,
    		@Y4								Int,
    		@M5								Tinyint,
    		@Y5								Int,
    		@M6								Tinyint,
    		@Y6								Int,
    		@M7								Tinyint,
    		@Y7								Int,
    		@MinTransactionDate				DateTime,
    		@MaxTransactionDate				DateTime,
    		
			@chkCostSalesEditorGL_0			Varchar(10),
			@optZeroCostOverride_0			Varchar(10),
			@optZeroCostOverride_1			Varchar(10),
			@optZeroCostOverride_2			Varchar(10),
			@optInventoryValuation_0		Varchar(10),
			@optInventoryValuation_1		Varchar(10),
			@optInventoryValuation_2		Varchar(10),
			@chkUseStockAdjGL_0				Varchar(10),
			@chkUseProductPurchasesGL_0		Varchar(10),
			@chkUseProductSalesGL_0    		Varchar(10),
			@Network_Identity_Number    	Varchar(20),
			@Contact1_Email					Varchar(50),
			@Contact2_Email					Varchar(50),

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	--Erick 2017/09/20
	SELECT @txtCSalesExclusions = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	--V6.3
	--Insert Supplier / GRV Info
	INSERT INTO @Tbl
	SELECT 
		'#*S*#'  + '~' +  
		Convert(varchar(10),IsNull(t.AO_Transactions_ID,-9)) + '~' +
		Convert(varchar(10),IsNull(t.AO_Suppliers_ID,-9)) + '~' +
		Replace(IsNull(s.Supplier_Name,''),'~','') + '~' +
		Replace(IsNull(c.[Description],''),'~','') + '~' +													--Credit_Terms					Varchar(20)
		Replace(IsNull(c.Terms_Value,''),'~','') + '~' +													--Credit_Terms_Value			Int
		Convert(varchar(20),IsNull(s.Credit_Limit,0)) + '~' +
		Convert(varchar(20),IsNull(t.Document_Date,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Convert(varchar(10),IsNull(t.AO_GRV_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(t.Trade_Discount_Total,0)) + '~' +										--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Rebate_Discount_Total,0)) + '~' +										--H_Rebate_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Other_Discount_Total,0)) + '~' +										--H_Other_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Net_Amount,0)) + '~' +													--H_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Tax_Amount,0)) + '~' +											--H_Total_Tax_Amount			Decimal(18,4)
		Convert(varchar(20),IsNull(t.Total_Amount,0)) + '~' +												--H_Total_Amount				Decimal(18,4)
		Convert(varchar(20),IsNull(t.Payment_Amount,0)) + '~' +												--H_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(t.Settlement_Discount,0)) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +											--H_Slu_AW_Active_ID			Int
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +								--H_Date_Captured				Datetime		
		Convert(varchar(20),IsNull(g.Date_Received,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(d.AP_Products_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(d.Qty,0)) + '~' +
		Convert(varchar(20),IsNull(d.Unit_Price,0)) + '~' +
		Convert(varchar(20),IsNull(d.Trade_Discount_Amount,0)) + '~' +										--D_Trade_Discount_Total		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Rebate_Discount_Amount,0)) + '~' +										--D_Rebate_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Other_Discount_Amount,0)) + '~' +										--D_Other_Discount_Amount		Decimal(18,4)
		Convert(varchar(20),IsNull(d.Net_Amount,0)) + '~' +													--D_Net_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Tax_Amount,0)) + '~' +													--D_Tax_Amount					Decimal(18,4)
		Convert(varchar(20),IsNull(d.Total_Cost,0)) + '~' +													--D_Total_Cost					Decimal(18,4)
		Convert(varchar(5),IsNull(d.Slu_AW_Active_ID,255)) + '~' +											--D_Slu_AW_Active_ID			Int		
		Convert(varchar(20),IsNull(d.Date_Captured,'1900-01-01'),120) + '~' +								--D_Date_Captured				Datetime		
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
 		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted  
 		Replace(IsNull(m.[Description],''),'~','') + '~' +													--Product_Manufacturer			Varchar(50) 
		Replace(IsNull(y.[Description],''),'~','') + '~' +													--Product_Types					Varchar(50) 
		Replace(IsNull(r.[Description],''),'~','') + '~' +													--Product_Groups				Varchar(50)
		Convert(varchar(10),IsNull(d.AO_GRV_Details_ID,-9)) + '~' +  

		--  XXXXX  Erick 2017-10-20
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AO_Transactions t
		Inner Join AO_Suppliers s
			On t.AO_Suppliers_ID = s.AO_Suppliers_ID
		Inner Join Slu_AW_Credit_Terms c
			On s.Slu_AW_Credit_Terms_ID = c.Slu_AW_Credit_Terms_ID
		Left Outer Join AO_GRV g
			On t.AO_GRV_ID = g.AO_GRV_ID
		Left Outer Join AO_GRV_Details d
			On t.AO_GRV_ID = d.AO_GRV_ID
		Left Outer Join AP_Products p
			On p.AP_Products_ID = d.AP_Products_ID
		Left Join Lup_AP_Product_Manufacturers m
			On p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID
		Left Join Lup_AP_Product_Types y
			On p.Lup_AP_Product_Types_ID = y.Lup_AP_Product_Types_ID	
		Left Join Lup_AP_Product_Groups r
			On p.Lup_AP_Product_Groups_ID = r.Lup_AP_Product_Groups_ID
	WHERE t.Date_Captured > @LastDayEND
	OR g.Date_Captured > @LastDayEND
	
	--V6.3
	--Product Adjustments
	INSERT INTO @Tbl
	SELECT 
		'#*A*#'  + '~' +
		Convert(varchar(10),IsNull(i.AP_Products_ID,-9)) + '~' +
		Replace(IsNull(p.Product_Code,''),'~','') + '~' +													--								Varchar(20)
		Replace(IsNull(p.[Description],''),'~','') + '~' +													--Product_Description			Varchar(50)
		Convert(varchar(5),IsNull(Sys_AP_Adjustment_Types_ID,255)) + '~' +
		Convert(varchar(20),IsNull(Previous_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(Previous_On_Hand,0)) + '~' +
		Convert(varchar(20),IsNull(New_Last_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_Average_Cost,0)) + '~' +
		Convert(varchar(20),IsNull(New_On_Hand,0)) + '~' +
		Replace(IsNull(Note,''),'~','') + '~' +																--								Varchar(70)
		Convert(varchar(20),IsNull(i.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(10),IsNull(i.AP_Inventory_Adjustments_ID,-9)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted	

		--  XXXXX  Erick 2017-10-20
		Convert(varchar(10),IsNull(i.[User_ID],-9))															--User_ID						Int
	From AP_Inventory_Adjustments i
			Left Outer Join AP_Products p
				On p.AP_Products_ID = i.AP_Products_ID	
	WHERE i.Date_Captured > @LastDayEND
	
	--V6.3
	--GL Accounts Info
	INSERT INTO @Tbl
	SELECT 
		'#*G*#'  + '~' + 
 		Convert(varchar(10),IsNull(aa.AB_Accounts_ID,-9)) + '~' +
		Replace(IsNull(aa.[Description],''),'~','') + '~' +													--Account_Description			Varchar(50)
		Replace(IsNull(aa.Account_Number,''),'~','') + '~' +
		Replace(IsNull(ac.[Description],''),'~','') + '~' +													--Account_Categories			Varchar(100)
		Replace(IsNull(tc.[Description],''),'~','') + '~' +													--Tax_Codes						Varchar(50)
		Convert(varchar(18),IsNull(tc.Tax_Rate,0)) + '~' +													--								Char(1)
		Replace(IsNull(cc.[Description],''),'~','') + '~' +													--Account_Cost_Centers			Varchar(50)
		Convert(varchar(20),IsNull(aa.AB_Account_Balance,0)) + '~' +
		Convert(varchar(5),IsNull(aa.AW_YesNo_Controllable_ID,255)) + '~' +
		Convert(varchar(20),IsNull(aa.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(aa.Slu_AW_Active_ID,255)) + '~' +
		Replace(IsNull(ag.[Description],''),'~','') + '~' +													--Account_Groups				Varchar(50)
		Replace(IsNull(ad.[Description],''),'~','') + '~' +													--Account_Divisions				Varchar(50)
		Replace(IsNull(dp.[Description],''),'~','') + '~' +													--Account_Departments			Varchar(50)
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted		
		
		Convert(varchar(5),IsNull(ca.Control_Number,255)) + '~' +											--Control_Number				Integer
		Replace(IsNull(ca.[Description],''),'~','') + '~' +													--Control_Account				Varchar(50)	
		Replace(IsNull(ca.[User_Description],''),'~','') + '~' +											--Control_Account_User			Varchar(50)	
		Convert(varchar(5),IsNull(ca.Control_Type,255))														--Control_Type					Integer
	FROM AB_Accounts aa
		Inner Join Sys_AB_Account_Categories ac
			On aa.Sys_AB_Account_Categories_ID = ac.Sys_AB_Account_Categories_ID
		Inner Join Sys_AW_Tax_Codes tc
			On aa.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
		Inner Join Lup_AB_Cost_Centers cc
			On aa.Lup_AB_Cost_Centers_ID = cc.Lup_AB_Cost_Centers_ID
		Inner Join Lup_AB_Account_Groups ag
			On aa.Lup_AB_Account_Groups_ID = ag.Lup_AB_Account_Groups_ID
		Inner Join Lup_AB_Account_Divisions ad
			On aa.Lup_AB_Account_Divisions_ID = ad.Lup_AB_Account_Divisions_ID
		Inner Join Lup_AB_Account_Departments dp
			On aa.Lup_AB_Account_Departments_ID = dp.Lup_AB_Account_Departments_ID

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

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

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

		--  XXXXX  Erick 2017-10-20
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE t.Date_Captured > @LastDayEND
	
	INSERT INTO @Tbl
 	SELECT
 		'#*T*#'  + '~' + 
		Convert(varchar(10),IsNull(t.AB_GL_Transactions_ID,-9)) + '~' + 
		Replace(Replace(IsNull(t.[Description],''),'~',''), CHAR(13) + CHAR(10) , ', ' ) + '~' +			--GL_Description					Varchar(50)
		Convert(varchar(5),IsNull(t.Sys_AB_Transaction_Types_ID,255)) + '~' + 
		Convert(varchar(10),IsNull(t.AB_Accounts_ID,-9)) + '~' +  
		Replace(IsNull(a.[Description],''),'~','') + '~' +													--Account_Description				Varchar(50)
		Convert(varchar(20),IsNull(t.AB_Transaction_Date,'1900-01-01'),120) + '~' + 
		Replace(IsNull(t.AB_Source_Ref,''),'~','') + '~' + 
		Convert(varchar(5),IsNull(t.Slu_AW_Months_ID,255)) + '~' +  
		Convert(varchar(5),IsNull(t.Slu_AW_Years_ID,255)) + '~' +
		Replace(IsNull(t.AB_Transaction_Ref,''),'~','') + '~' + 
		Convert(varchar(20),IsNull(t.AB_Transaction_Amount,0)) + '~' + 
		Convert(varchar(20),IsNull(t.Date_Captured,'1900-01-01'),120) + '~' +
		Convert(varchar(5),IsNull(t.Slu_AW_Active_ID,255)) + '~' +
		Convert(varchar(20),IsNull(@Today,'1900-01-01'),120) + '~' +										--Date_Extracted

		--  XXXXX  Erick 2017-10-20
		Convert(varchar(10),IsNull(t.[User_ID],-9))															--User_ID						Int
	FROM AB_GL_Transactions t
		INNER JOIN AB_GL_Transactions_Audit x
			On t.AB_GL_Transactions_ID = x.AB_GL_Transactions_ID
		LEFT JOIN AB_Accounts a
			On t.AB_Accounts_ID = a.AB_Accounts_ID
	WHERE x.Date_Captured > @LastDayEND

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

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

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

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

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

	SELECT Rec FROM @Tbl ORDER BY UniqueID

SET NOCOUNT OFF
GO



IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_Sales_Analysis_Year]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Year]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Analysis_Year
--Purpose       :PRECEDING 12 MONTHS Sales Analysis with Rolling 12 months UNIT SALES
--              :Shows SALES DATA for products sold IN THE PRECEDING 12 MONTHS
--              :
--Funtionality  :
--Date          :2004/12/26
--Authors       :TB
--MODS:         :
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Year]
    (
        @Filter varchar(50),
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @InterCompany tinyint,
        @Target decimal(9,3),
        @Projected decimal(9,3),
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ElapsedDays tinyint,
            @YearStartDate datetime,
            @TargetPerc float,
            @Jan_Qty decimal(9,3),
            @Feb_Qty decimal(9,3),
            @Mar_Qty decimal(9,3),
            @Apr_Qty decimal(9,3),
            @May_Qty decimal(9,3),
            @Jun_Qty decimal(9,3),
            @Jul_Qty decimal(9,3),
            @Aug_Qty decimal(9,3),
            @Sep_Qty decimal(9,3),
            @Oct_Qty decimal(9,3),
            @Nov_Qty decimal(9,3),
            @Dec_Qty decimal(9,3)


    SET @ElapsedDays = ISNULL(DAY(@ReportDate), 1)
    SET @YearStartDate = DATEADD(yy, -1, @EndDate)
    SET @TargetPerc = @Target / 100



--------------------------------------------------
--> DROP the WORK table AS_RPT_Sales_Analysis_Temp
--------------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AS_RPT_Sales_Analysis_Temp]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AS_RPT_Sales_Analysis_Temp]


--------------------------------------------------
--> SELECT DISTINCT rolling 12 months products with sales 
--------------------------------------------------
    DECLARE @Sales_12_Months table
                (
                    [CompanyID] int,
                    [HeaderID] int,
                    [Filter] varchar(100),
                    [ProductID] int,
                    [Description] varchar(100),
                    [Code] varchar(20),
                    [Qty] decimal(9,3),
                    [AvgQty] decimal(9,3),
                    [TargetQty] decimal(9,3),
                    [ProjQty] decimal(9,3),
                    [Amount] money,
                    [AvgAmt] money,
                    [TargetAmt] money,
                    [ProjAmt] money,
                    [Total] money,
                    [GP] money,
                    [GPPerc] decimal(9,3),
                    [Jan_Qty] decimal(9,3),
                    [Feb_Qty] decimal(9,3),
                    [Mar_Qty] decimal(9,3),
                    [Apr_Qty] decimal(9,3),
                    [May_Qty] decimal(9,3),
                    [Jun_Qty] decimal(9,3),
                    [Jul_Qty] decimal(9,3),
                    [Aug_Qty] decimal(9,3),
                    [Sep_Qty] decimal(9,3),
                    [Oct_Qty] decimal(9,3),
                    [Nov_Qty] decimal(9,3),
                    [Dec_Qty] decimal(9,3)
                )

    IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		IF @ActiveOnly = 1
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_Active_ID = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
					(
						CompanyID,
						ProductID
					)
					SELECT DISTINCT
						d.AW_User_Companies_ID,
						d.AP_Products_ID
					FROM AS_Transaction_Details d
						INNER JOIN AS_Transactions h
							ON d.AS_Transactions_ID = h.AS_Transactions_ID
						INNER JOIN AC_Customers c
							ON c.AC_Customers_ID = h.AC_Customers_ID
						INNER JOIN AP_Products p
							ON d.AP_Products_ID = p.AP_Products_ID
					WHERE d.AW_User_Companies_ID = @CompanyID AND
						c.Sys_AC_Account_Types_ID <> 3 AND
						d.Slu_AW_Active_ID = 1 AND
						(h.Sys_AW_Transaction_Types_ID = 3 OR 
						 h.Sys_AW_Transaction_Types_ID = 4) AND
						dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
						p.Slu_AW_Active_ID = 1
			END
		END --@ActiveOnly = 1
		ELSE
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					INNER JOIN AC_Customers c
						ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					c.Sys_AC_Account_Types_ID <> 3 AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1
			END
		END
    END      --Exclude Inter-Company Sales
    ELSE    
	BEGIN
		IF @ActiveOnly = 1
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_Active_ID = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
					(
						CompanyID,
						ProductID
					)
					SELECT DISTINCT
						d.AW_User_Companies_ID,
						d.AP_Products_ID
					FROM AS_Transaction_Details d
						INNER JOIN AS_Transactions h
							ON d.AS_Transactions_ID = h.AS_Transactions_ID
						--INNER JOIN AC_Customers c
						--	ON c.AC_Customers_ID = h.AC_Customers_ID
						INNER JOIN AP_Products p
							ON d.AP_Products_ID = p.AP_Products_ID
					WHERE d.AW_User_Companies_ID = @CompanyID AND
						d.Slu_AW_Active_ID = 1 AND
						(h.Sys_AW_Transaction_Types_ID = 3 OR 
						 h.Sys_AW_Transaction_Types_ID = 4) AND
						dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
						p.Slu_AW_Active_ID = 1
			END
		END
		ELSE
		BEGIN
			IF @NonStock = 1
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1 AND
					p.Slu_AW_YesNo_Non_Stock_Item = 0
			END
			ELSE
			BEGIN
				INSERT INTO @Sales_12_Months
				(
					CompanyID,
					ProductID
				)
				SELECT DISTINCT
					d.AW_User_Companies_ID,
					d.AP_Products_ID
				FROM AS_Transaction_Details d
					INNER JOIN AS_Transactions h
						ON d.AS_Transactions_ID = h.AS_Transactions_ID
					--INNER JOIN AC_Customers c
					--	ON c.AC_Customers_ID = h.AC_Customers_ID
					INNER JOIN AP_Products p
						ON d.AP_Products_ID = p.AP_Products_ID
				WHERE d.AW_User_Companies_ID = @CompanyID AND
					d.Slu_AW_Active_ID = 1 AND
					(h.Sys_AW_Transaction_Types_ID = 3 OR 
					 h.Sys_AW_Transaction_Types_ID = 4) AND
					dbo.fn_AS_Product_Has_Sales(@CompanyID, @YearStartDate, @EndDate) = 1
			END
		END
    END



--------------------------------------------------
--> ADD static data to @Sales_12_Months table
--------------------------------------------------
    SET @sql = ' UPDATE sp '
    
    IF @Filter = 'Type'
        BEGIN
			UPDATE sp
			SET HeaderID = o.Lup_AP_Product_Types_ID,
				Filter = o.[Description],
				[Description] = p.[Description],
				Code = p.Product_Code
			FROM @Sales_12_Months sp
				INNER JOIN AP_Products p
					ON p.AP_Products_ID = sp.ProductID
				LEFT JOIN Lup_AP_Product_Types o
					ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID
        END
    ELSE
    IF @Filter = 'Groups'
        BEGIN
            UPDATE sp
            SET HeaderID = o.Lup_AP_Product_Groups_ID,
                Filter = o.[Description],
                [Description] = p.[Description],
                Code = p.Product_Code
            FROM @Sales_12_Months sp
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = sp.ProductID
                LEFT JOIN Lup_AP_Product_Groups o
                    ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID
        END
    ELSE
    IF @Filter = 'Department'
        BEGIN
            UPDATE sp
            SET HeaderID = o.Lup_AP_Product_Departments_ID,
                Filter = o.[Description],
                [Description] = p.[Description],
                Code = p.Product_Code
            FROM @Sales_12_Months sp
                INNER JOIN AP_Products p
                    ON p.AP_Products_ID = sp.ProductID
                LEFT JOIN Lup_AP_Product_Departments o
                    ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID
        END



--------------------------------------------------
--> ADD MONTHLY Sales Qty for each Sales Product
--------------------------------------------------
	--JAN
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jan_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jan AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jan_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jan AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--FEB	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Feb_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Feb AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Feb_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Feb AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Mar	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Mar_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Mar AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Mar_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Mar AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END

	--Apr
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Apr_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Apr AND
							  c.Sys_AC_Account_Types_ID <> 3 AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Apr_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Apr AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--May
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET May_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @May AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET May_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @May AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Jun
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jun_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jun AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jun_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jun AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Jul
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Jul_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jul AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Jul_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Jul AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Aug	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Aug_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Aug AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Aug_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Aug AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Sep	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Sep_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Sep AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Sep_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Sep AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Oct	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Oct_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Oct AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Oct_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Oct AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Nov	
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Nov_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Nov AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Nov_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Nov AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
	--Dec
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		UPDATE sp
		SET Dec_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
							INNER JOIN AC_Customers c
								ON c.AC_Customers_ID = f.AC_Customers_ID								
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Dec AND
							  c.Sys_AC_Account_Types_ID <> 3 AND							  
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	ELSE
	BEGIN
		UPDATE sp
		SET Dec_Qty = (
						SELECT SUM(e.Quantity)
						FROM AS_Transaction_Details e
							INNER JOIN AS_Transactions f
								ON f.AS_Transactions_ID = e.AS_Transactions_ID
						WHERE e.AP_Products_ID = sp.ProductID AND
							  dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = @Dec AND
							 (f.Sys_AW_Transaction_Types_ID = 3 OR
							  f.Sys_AW_Transaction_Types_ID = 4)
	--                    GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)
						)
		FROM @Sales_12_Months sp
	END
	
--------------------------------------------------
--> INSERT everyting into NEW AS_RPT_Sales_Analysis_Temp
--------------------------------------------------
    SELECT *
    INTO AS_RPT_Sales_Analysis_Temp
    FROM @Sales_12_Months
    ORDER BY [Filter], [HeaderID], [Description]


--------------------------------------------------
--> INSERT the CURRENT MONTH sales data
--------------------------------------------------
    SET @sql = ' DECLARE @Current_Month table ( ' +
                                                ' [ProductID] int, ' +
                                                ' [Qty] decimal(9,3), ' +
                                                ' [AvgQty] decimal(9,3), ' +
                                                ' [ProjQty] decimal(9,3), ' +
                                                ' [Amount] money, ' +
                                                ' [AvgAmt] money, ' +
                                                ' [ProjAmt] money, ' +
                                                ' [TargetQty] decimal(9,3), ' +
                                                ' [TargetAmt] money, ' +
                                                ' [Total] money, ' +
                                                ' [GP] money, ' +
                                                ' [GPPerc] decimal(9,3) ) '


    SET @sql = @sql + ' INSERT INTO @Current_Month '

    SET @sql = @sql + ' SELECT '
    
    SET @sql = @sql + ' d.AP_Products_ID, '
    SET @sql = @sql + ' SUM(d.Quantity), '
    SET @sql = @sql + ' ROUND(SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2), '
    SET @sql = @sql + ' ROUND((SUM(d.Quantity) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2), '
    
    
    SET @sql = @sql + ' SUM(d.Extended_Amount - d.Tax_Amount), '
    SET @sql = @sql + ' ROUND(SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ', 2), '
    SET @sql = @sql + ' ROUND((SUM(d.Extended_Amount - d.Tax_Amount) / ' + CONVERT(varchar(10), @ElapsedDays) + ') * ' + CONVERT(varchar(10), @Projected) + ', 2), '

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(x.Quantity / 12) + SUM(x.Quantity / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = y.AC_Customers_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '
		SET @sql = @sql + ' ), 0), '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM(x.Quantity / 12) + SUM(x.Quantity / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4)'
		SET @sql = @sql + ' ), 0), '	
	END    
    
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM((x.Extended_Amount - x.Tax_Amount) / 12) + SUM((x.Extended_Amount - x.Tax_Amount) / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = y.AC_Customers_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4) '
		SET @sql = @sql + '  AND c.Sys_AC_Account_Types_ID <> 3 '		
		SET @sql = @sql + ' ), 0), '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(( '
		SET @sql = @sql + ' SELECT SUM((x.Extended_Amount - x.Tax_Amount) / 12) + SUM((x.Extended_Amount - x.Tax_Amount) / 12) * ' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + ' FROM AS_Transaction_Details x '
		SET @sql = @sql + '     INNER JOIN AS_Transactions y '
		SET @sql = @sql + '         ON y.AS_Transactions_ID = x.AS_Transactions_ID '
		SET @sql = @sql + ' WHERE x.AP_Products_ID = d.AP_Products_ID '
		SET @sql = @sql + '  AND (y.Transaction_Date >= ''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + '  AND  y.Transaction_Date <= ''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + '  AND (y.Sys_AW_Transaction_Types_ID = 3 OR '
		SET @sql = @sql + '       y.Sys_AW_Transaction_Types_ID = 4)'
		SET @sql = @sql + ' ), 0), '
	END


    SET @sql = @sql + ' SUM(d.Extended_Amount), '
    SET @sql = @sql + ' SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)), '
    SET @sql = @sql + ' CASE WHEN SUM(d.Extended_Amount - d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN SUM((d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) / SUM(d.Extended_Amount - d.Tax_Amount) * 100 '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END '

    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 '

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + '     INNER JOIN AC_Customers c '
		SET @sql = @sql + '         ON c.AC_Customers_ID = h.AC_Customers_ID '
	END

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

	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '				
	END

    SET @sql = @sql + ' GROUP BY d.AP_Products_ID '


    SET @sql = @sql + ' UPDATE b '
    SET @sql = @sql + ' SET b.Qty = a.Qty, '
    SET @sql = @sql + '     b.AvgQty = a.AvgQty, '
    SET @sql = @sql + '     b.ProjQty = a.ProjQty, '
    SET @sql = @sql + '     b.Amount = a.Amount, '
    SET @sql = @sql + '     b.AvgAmt = a.AvgAmt, '
    SET @sql = @sql + '     b.ProjAmt = a.ProjAmt, '
    SET @sql = @sql + '     b.TargetQty = a.TargetQty, '
    SET @sql = @sql + '     b.TargetAmt = a.TargetAmt, '
    SET @sql = @sql + '     b.Total = a.Total, '
    SET @sql = @sql + '     b.GP = a.GP, '
    SET @sql = @sql + '     b.GPPerc = a.GPPerc '
    SET @sql = @sql + ' FROM @Current_Month a '
    SET @sql = @sql + '     INNER JOIN AS_RPT_Sales_Analysis_Temp b '
    SET @sql = @sql + '         ON a.ProductID = b.ProductID '
    SET @sql = @sql + ' WHERE a.ProductID = b.ProductID '


    EXEC (@sql)


--------------------------------------------------
--> FETCH the REPORT data
--------------------------------------------------
    SET @sql = ' SELECT st.* '
    SET @sql = @sql + ' FROM AS_RPT_Sales_Analysis_Temp st '
    SET @sql = @sql + '     INNER JOIN AP_Products p '
    SET @sql = @sql + '         ON p.AP_Products_ID = st.ProductID '
    SET @sql = @sql + ' WHERE p.AP_Products_ID = st.ProductID '

    IF @ActiveOnly = 1     --Only Active Products
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_Active_ID = 1 '
        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 st.[Filter], st.[Description] '
    
    
    EXEC (@sql)


---------------------------------------------
    DROP TABLE AS_RPT_Sales_Analysis_Temp
---------------------------------------------
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_Sales_Analysis_Month]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Month]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Sales_Analysis_Month
--Purpose       :CURRENT MONTH Sales Analysis with Rolling 12 months UNIT SALES
--              :Shows SALES DATA for products sold in the CURRENT MONTH ONLY
--              :    caused by @StartDate and @EndDate REQUIRED in WHERE clause
--Funtionality  :NB NB @sql string size near its limit of 8000 (7531) characters
--Date          :2004/12/22
--Authors       :TB
--MODS:         :
--V6.3	RL	2017-06-14	:Fixed - Intercompany excluded in quantity sum
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Sales_Analysis_Month]
    (
        @Filter varchar(30),
        @ReportDate datetime,
        @StartDate datetime,
        @EndDate datetime,
        @ActiveOnly tinyint,
        @NonStock tinyint,
        @InterCompany tinyint,
        @Target decimal(9,3),
        @Projected decimal(9,3),
        @CompanyID int,
        @Jan varchar(6),
        @Feb varchar(6),
        @Mar varchar(6),
        @Apr varchar(6),
        @May varchar(6),
        @Jun varchar(6),
        @Jul varchar(6),
        @Aug varchar(6),
        @Sep varchar(6),
        @Oct varchar(6),
        @Nov varchar(6),
        @Dec varchar(6)
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @ElapsedDays tinyint,
            @YearStartDate datetime,
            @TargetPerc float

    SET @ElapsedDays = ISNULL(DAY(@ReportDate), 1)
    SET @YearStartDate = DATEADD(yy, -1, @EndDate)
    SET @TargetPerc = @Target / 100

    SET @sql = 'SELECT '
    
    SET @sql = @sql + 'MAX(d.AW_User_Companies_ID)AS[CompanyID],'
    
    IF @Filter = 'Type'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Types_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    ELSE
    IF @Filter = 'Groups'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Groups_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    ELSE
    IF @Filter = 'Department'
    SET @sql = @sql +
                'MAX(o.Lup_AP_Product_Departments_ID)AS[HeaderID],' +
                'MAX(o.[Description])AS[Filter],'
    
    SET @sql = @sql + 'd.AP_Products_ID AS [ProductID],'
    SET @sql = @sql + 'MAX(ISNULL(p.[Description],''''))AS[Description],'
    SET @sql = @sql + 'MAX(ISNULL(p.Product_Code,''''))AS[Code],'
    
    SET @sql = @sql + 'SUM(d.Quantity)AS[Qty],'
    SET @sql = @sql + 'ROUND(SUM(d.Quantity)/' + CONVERT(varchar(10), @ElapsedDays) + ',2)AS[AvgQty],'
    SET @sql = @sql + 'ROUND((SUM(d.Quantity)/' + CONVERT(varchar(10), @ElapsedDays) + ')* ' + CONVERT(varchar(10), @Projected) + ',2)AS[ProjQty],'
    
    SET @sql = @sql + 'SUM(d.Extended_Amount-d.Tax_Amount)AS[Amount],'
    SET @sql = @sql + 'ROUND(SUM(d.Extended_Amount-d.Tax_Amount)/' + CONVERT(varchar(10), @ElapsedDays) + ',2)AS[AvgAmt],'
    SET @sql = @sql + 'ROUND((SUM(d.Extended_Amount-d.Tax_Amount)/' + CONVERT(varchar(10), @ElapsedDays) + ')* ' + CONVERT(varchar(10), @Projected) + ',2)AS[ProjAmt],'
    
	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(x.Quantity/12)+SUM(x.Quantity/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=y.AC_Customers_ID	'							
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + '),0)AS[TargetQty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(x.Quantity/12)+SUM(x.Quantity/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + '),0)AS[TargetQty],'
	END
	    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(( '
		SET @sql = @sql + 'SELECT SUM((x.Extended_Amount-x.Tax_Amount)/12)+SUM((x.Extended_Amount-x.Tax_Amount)/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=y.AC_Customers_ID	'									
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3'				
		SET @sql = @sql + '),0)AS[TargetAmt],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(( '
		SET @sql = @sql + 'SELECT SUM((x.Extended_Amount-x.Tax_Amount)/12)+SUM((x.Extended_Amount-x.Tax_Amount)/12)*' + CONVERT(varchar(20), @TargetPerc) + ' '
		SET @sql = @sql + 'FROM vw_ASTD x '
		SET @sql = @sql + 'INNER JOIN vw_AST y '
		SET @sql = @sql + 'ON y.AS_Transactions_ID=x.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE x.AP_Products_ID=d.AP_Products_ID '
		SET @sql = @sql + 'AND (y.Transaction_Date>=''' + CONVERT(varchar(30), @YearStartDate) + ''' '
		SET @sql = @sql + 'AND  y.Transaction_Date<=''' + CONVERT(varchar(30), @EndDate)  + ''') '
		SET @sql = @sql + 'AND (y.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'y.Sys_AW_Transaction_Types_ID=4)'
		SET @sql = @sql + '),0)AS[TargetAmt],'
	END    
    
    SET @sql = @sql + 'SUM(d.Extended_Amount) AS [Total], '
    SET @sql = @sql + 'SUM((d.Extended_Amount-d.Tax_Amount)-(d.Quantity*d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + 'CASE WHEN SUM(d.Extended_Amount-d.Tax_Amount)<>0 '
    SET @sql = @sql + 'THEN SUM((d.Extended_Amount-d.Tax_Amount)-(d.Quantity*d.Unit_Cost))/SUM(d.Extended_Amount-d.Tax_Amount)*100 '
    SET @sql = @sql + 'ELSE 0.00 '
    SET @sql = @sql + 'END AS [GPPerc],'
    
  	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jan + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jan_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jan + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jan_Qty],'
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Feb + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Feb_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Feb + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Feb_Qty], '
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Mar + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Mar_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Mar + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Mar_Qty],'
	END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Apr + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Apr_Qty], '
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Apr + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Apr_Qty],'
    END

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @May + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '				
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[May_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @May + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[May_Qty],'
    END
  
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jun + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jun_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jun + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jun_Qty],'
    END    
    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jul + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jul_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Jul + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Jul_Qty],'    
    END
    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Aug + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Aug_Qty],'
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Aug + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Aug_Qty],'
	END	
	
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Sep + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Sep_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) = ''' + @Sep + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Sep_Qty],'
    END    
  
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Oct + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Oct_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Oct + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Oct_Qty],'
    END    

 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Nov + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Nov_Qty],'
    END
    ELSE
    BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Nov + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Nov_Qty],'
	END
	    
 	IF @InterCompany = 1      --Exclude Inter-Company Sales
	BEGIN  
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'INNER JOIN AC_Customers c '
		SET @sql = @sql + 'ON c.AC_Customers_ID=f.AC_Customers_ID '		
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)=''' + @Dec + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '		
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)'
		SET @sql = @sql + '),0)AS[Dec_Qty] '
	END
	ELSE
	BEGIN
		SET @sql = @sql + 'ISNULL(('
		SET @sql = @sql + 'SELECT SUM(e.Quantity) '
		SET @sql = @sql + 'FROM vw_ASTD e '
		SET @sql = @sql + 'INNER JOIN vw_AST f '
		SET @sql = @sql + 'ON f.AS_Transactions_ID=e.AS_Transactions_ID '
		SET @sql = @sql + 'WHERE e.AP_Products_ID=d.AP_Products_ID AND '
		SET @sql = @sql + 'dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date)= ''' + @Dec + ''' AND '
		SET @sql = @sql + '(f.Sys_AW_Transaction_Types_ID=3 OR '
		SET @sql = @sql + 'f.Sys_AW_Transaction_Types_ID=4) '
		SET @sql = @sql + 'GROUP BY dbo.fn_AS_Get_MonthYear_Number(f.Transaction_Date) '
		SET @sql = @sql + '),0)AS[Dec_Qty] '
	END	
    
    SET @sql = @sql + 'FROM vw_ASTD d '
    SET @sql = @sql + 'INNER JOIN vw_AST 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 '
    
    IF @Filter = 'Type'
    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 @Filter = 'Groups'
    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 @Filter = 'Department'
    SET @sql = @sql +
            'LEFT JOIN Lup_AP_Product_Departments o ' +
            'ON p.Lup_AP_Product_Departments_ID=o.Lup_AP_Product_Departments_ID '

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

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

    IF @InterCompany = 1      --Exclude Inter-Company Sales
        BEGIN
            SET @sql = @sql + 'AND c.Sys_AC_Account_Types_ID<>3 '
        END
    
    SET @sql = @sql + 'GROUP BY d.AP_Products_ID '
    
    SET @sql = @sql + 'ORDER BY [Filter],[Description] '
    
    --PRINT @sql
    
    EXEC (@sql)
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_DayEnd_Customer_Sales]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Customer_Sales]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Customer_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by CUSTOMER by Sales Person by Filter
--Date          :2003/08/27
--Authors       :TB
--MODS:         :15/04/04 - Added 'Cashier' filter
--2004.5.0      :07/03/11 - Modified [Selling] field to reflect Unit_Price ONLY
--              :08/03/11 - Added ISNULL validation of filter descriptions
--V6.3	RL	2017/09/10	:Added Sys_AW_Transaction_Types_ID Option
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Customer_Sales]
    (
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
		@Sys_AW_Transaction_Types_ID int,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(5000)

-- SET @Option = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


    SET @sql = ' SELECT '

    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 + ' r.Lup_AS_Reps_ID AS [RepID], '
    SET @sql = @sql + ' ISNULL(r.[Description], '''') AS [RepName], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '

--     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 + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    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 + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    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 '


--------------------------------------------------------------------------------------------
--> Floor_Rep_Sales extracts Rep from AS_Transactions rather than AC_Customers
--------------------------------------------------------------------------------------------
--     SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
--     SET @sql = @sql + '          ON c.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    SET @sql = @sql + '      LEFT JOIN Lup_AS_Reps r '
    SET @sql = @sql + '          ON h.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '
--------------------------------------------------------------------------------------------


    IF @Option = 'Type'
        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 @Option = 'Groups'
        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 @Option = 'Department'
        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 @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        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 @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Option = 'Sales Area'
        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 @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_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.Slu_AW_Active_ID = 1'



		If @Sys_AW_Transaction_Types_ID <> 0
		BEGIN
			SET @sql = @sql + '     AND (h.Sys_AW_Transaction_Types_ID = ' + CONVERT(varchar(10), @Sys_AW_Transaction_Types_ID) + ')  ' 
        END

    SET @sql = @sql +
        ' ORDER BY [Customer], [RepID], [Filter], [TranDate] '

--PRINT @sql

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

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

AS

SET NOCOUNT ON

    DECLARE @New_ID int

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

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


        END

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

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


	RETURN @New_ID


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Add_BO_To_SO]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Add_BO_To_SO
--Purpose       :Creates or updates a SO with BO Qty
--Date          :2017/09/10
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Add_BO_To_SO]
    (
		@DocumentID				Int = NULL,
		@ProductID				Int = NULL,
		@Back_Order				Decimal(9,3) = 0,

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

SET NOCOUNT ON

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

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

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

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

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

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

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

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

			SELECT @NewTransID = @SO_TransID

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

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

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

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

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

					EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
				END
			END

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

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

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

		IF @SO_TransID = 0
		BEGIN

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

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

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

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


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

			SELECT @NewTransID = Scope_Identity()

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

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

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

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment

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

				EXEC sp_AS_POS_Transaction_Comment_Insert_Update @OrigDocCommentID OUTPUT, @OrigDocComment
			END

		END

	END --@TransactionTypeID <> 16

		IF @Qty = 0
		BEGIN

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

			SELECT @NewDiscount = 0
			SET @NewTax = 0

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

		END
		ELSE
		BEGIN

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

			SET @NewTax = 0

			IF @Tax <> 0
			BEGIN

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

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

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

			END
		END

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

		--Insert detail record into Sales order
		IF @DocumentDetailsID = 0
		BEGIN
			INSERT AS_Transaction_Details
				(
					AS_Transactions_ID,
					AP_Products_ID,
					Quantity,
					Back_Order,

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

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

					ISNULL(@Cost,0),
					ISNULL(@Price,0),
					ISNULL(@OriginalPrice,0),
					ISNULL(@NewDiscount,0),
					ISNULL(@NewTax,0),
					ISNULL(@NewTotalAmount,0),
					NULL,

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

			SELECT @DocumentDetailsID = Scope_Identity()
		END

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


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

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

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

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

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

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

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

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

		IF @chkSOAutoAddPO_DocType = '1'
		BEGIN

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

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

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

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

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

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

			END
								
			EXEC @AO_Order_Candidates_ID = sp_AO_Add_Product_To_Order_Candidates_RET @ProductID, @AO_Suppliers_ID, @Back_Order, @PONotes, @UserID ,@UserID , @CompanyID, @RemoteID
		END
	END
END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_CustomerRef_AssetNo]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_CustomerRef_AssetNo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AS_POS_CustomerRef_AssetNo
--Purpose       :Insert Customer Reference and Asset Number into AS_Transactions
--              :
--              :
--Date			:2002/12/30
--Authors		:TB
--Version		:1.0.0
--MODS          :09/01/03 - Increased AssetNo field size to 20
--V6.3	RL	2017-09-10	:Update Sales Order Customer_Reference And Comment
--						:SpSPOSTrans.dll does not sends it through as NULL. WTF!!!!
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_CustomerRef_AssetNo]
	(
		@TranID int,
        @CustomerRef varchar(15),
        @AssetNo varchar(20)
	)

AS

SET NOCOUNT ON

	Declare	@Date_Captured	Datetime,
			@SO_TranID		Int

    BEGIN
        UPDATE AS_Transactions
        SET Customer_Reference = ISNULL(@CustomerRef,''),
            Comment = ISNULL(@AssetNo,'')
        WHERE AS_Transactions_ID = @TranID

		SELECT @Date_Captured = Date_Captured
		FROM AS_Transactions
		WHERE AS_Transactions_ID = @TranID

		SET @SO_TranID = 0
		SELECT @SO_TranID = AS_Transactions_ID
		FROM AS_Transactions
		WHERE Date_Captured = @Date_Captured
		AND Sys_AW_Transaction_Types_ID = 16

		IF @SO_TranID <> 0
		BEGIN
			UPDATE AS_Transactions
			SET Customer_Reference = ISNULL(@CustomerRef,''),
				Comment = ISNULL(@AssetNo,'')
			WHERE AS_Transactions_ID = @SO_TranID
		END


    END


SET NOCOUNT OFF
GO
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          :
--V6.3	RL	2017-09-10	:Return Lup_AS_Rep_ID. Used as default Sales Rep dependant on system option
-------------------------------------------------------------------------------

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], '
	--V6.3 RL 2017/09/11
	SET @sql = @sql + ' a.Lup_AS_Reps_ID AS [SalesPersonID], ' 

    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
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
--V6.3	RL	2017-09-10	:Return Lup_AS_Rep_ID. Used as default Sales Rep dependant on system option
-------------------------------------------------------------------------------

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], '       
	--V6.3 RL 2017/09/11
	SET @sql = @sql + ' a.Lup_AS_Reps_ID AS [SalesPersonID], '

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

-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Lups
--Purpose       :User Catalog Lups
--Functionality : 
--Parameters    : 
--Date          :2001/11/17
--Authors       :TB
--MODS          :27/09/02 - Added ORDER BY Description for Applications LUP
--              :           and reversed User FirstName, Surname order
--              :02/10/02 - Added IsCashier & IsSupervisor as Choice 5 & 6
--              :25/07/03 - Option 3: Select ONLY ACTIVE Applications
--              :03/01/04 - Added IsDBAdmin, IsCRM, IsController, Delivery Methods
--              :           as Choice 7, 8, 9 & 10 for Credit Manager
--              :22/09/05 - Added IsAccountant as Choice 11
--2004.3.7      :12/09/07 - Added IsDataExporter as Choice 12
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor as Choice 13
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController as Choice 14
--2015.6.2 RGL  :2015-11-12 - Added Product Bins as Choice 16
--2015.6.3 RGL  :2017-09-11 - Added Till Payout as Choice 18
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Select_User_Lups]
    (
    	@Choice int
    )
AS

SET NOCOUNT ON

    BEGIN 
    	--> Active
    	IF @Choice = 1 
    		SELECT Slu_AW_Active_ID AS [ID], 
    			[Description] AS [Active] 
    		FROM Slu_AW_Active
    
    	--> User Companies
    	ELSE
    	IF @Choice = 2
    		SELECT AW_User_Companies_ID AS [ID], 
    			Company_Name AS [Company] 
    		FROM AW_User_Companies
    
    	--> Applications
    	ELSE 
    	IF @Choice = 3
    		SELECT Sys_AW_Applications_ID AS [ID],
    			[Description] AS [Applications]
    		FROM Sys_AW_Applications
            WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
    
    	--> Users
    	ELSE 
    	IF @Choice = 4
    		SELECT AW_Users_ID AS [ID],
    			    ISNULL(Surname, '') + ISNULL(' ' + FirstName, '') AS [User]
    		FROM AW_Users 
    		WHERE AW_Users_ID <> -1
    		ORDER BY Surname, FirstName
    
    	--> IsCashiers
    	ELSE 
    	IF @Choice = 5
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [Cashier]
    		FROM Slu_AW_YesNo 
    
    	--> IsSupervisor
    	ELSE 
    	IF @Choice = 6
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Supervisor]
    		FROM Slu_AW_YesNo 

    	--> IsDBAdmin
    	ELSE 
    	IF @Choice = 7
    		SELECT Slu_AW_YesNo_ID AS [ID],
                   ISNULL(Description, '') AS [DBAdmin]
    		FROM Slu_AW_YesNo 
    
    	--> IsCRM
    	ELSE 
    	IF @Choice = 8
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [CRM]
    		FROM Slu_AW_YesNo 
    
    	--> IsCreditController
    	ELSE 
    	IF @Choice = 9
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Controller]
    		FROM Slu_AW_YesNo 

        --> Delivery Methods
        ELSE
        IF @Choice = 10
          	SELECT Sys_AW_Delivery_Methods_ID as [ID],
                   ISNULL(Description, '') AS [Description]
            FROM Sys_AW_Delivery_Methods 

        --> IsAccountant
        ELSE
        IF @Choice = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [Accountant]
    		FROM Slu_AW_YesNo 

        --> IsDataExporter
        ELSE
        IF @Choice = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [DataExport]
    		FROM Slu_AW_YesNo 

        --> IsProcurementSupervisor
        ELSE
        IF @Choice = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [ProcureSuper]
    		FROM Slu_AW_YesNo
    		 
		--> IsLevyController
        ELSE
        IF @Choice = 14
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [LevyCont]
    		FROM Slu_AW_YesNo     		
		--> IsRecordManager
        ELSE
        IF @Choice = 15
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [RecordsManager]
    		FROM Slu_AW_YesNo     		

        ELSE
        IF @Choice = 16
    		SELECT Lup_AP_Product_Bins_ID AS [ID],
    			   ISNULL([Description], '') AS [ProductBins]
    		FROM Lup_AP_Product_Bins     		
        ELSE
        --> IsBinSuper
        IF @Choice = 17
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [BinSuper]
    		FROM Slu_AW_YesNo     		
        ELSE
        --> IsTillPayout
        IF @Choice = 18
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			   ISNULL(Description, '') AS [TillPayout]
    		FROM Slu_AW_YesNo     		

    END

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

-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Catalog
--Date          :2001/11/17
--Authors       :TB
--MODS          :02/10/02 - Added IsCashier & IsSupervisor
--              :20/12/03 - Added IsDBAdmin
--              :03/01/03 - Added IsAdministrator, IsController
--              :22/09/05 - Added IsAccountant
--2004.3.7      :12/09/07 - Added IsDataExporter
--2004.3.8      :30/04/08 - Added IsProcurementSupervisor
--2004.5.7 RGL  :2012-10-26 - Added IsLevyController
--2004.5.9 RGL  :2013-07-15 - Added IsRecordsManager
--2015.6.2 RGL  :2015-11-12 - Added Product Bins
--2015.6.3 RGL  :2017-09-11 - Added Till Payout
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Select_User_Catalog]
    (
    	@User_ID int    )

AS

SET NOCOUNT ON

    SELECT AW_Users_ID AS [ID], 
    	Surname AS [Surname], 
    	FirstName AS [First Name], 
    	UserName AS [User Name], 
    	[Password] AS [Password], 
    	User_Home_Tel_Number AS [Home Tel No], 
        User_Cell_Number AS [Cell No], 
    	User_Email AS [E-mail Address], 
    	Activation_Date AS [Activation Date], 
    	Deactivation_Date AS [Deactivation Date], 
    	Unsuccessful_Logins AS [Unsuccessful Logins], 
    	Sys_AW_Applications_ID AS [Applications],
        Slu_AW_Active_ID AS [Active],
        IsCashier AS [IsCashier],
        IsSupervisor AS [IsSupervisor],
        IsDBAdmin AS [IsDBAdmin],
        IsCRM AS [IsCRM],
        IsController AS [IsController],
        Sys_AW_Delivery_Methods_ID AS [Delivery Method],
        IsAccountant AS [IsAccountant],
        IsDataExporter AS [IsDataExporter],
        IsProcurementSupervisor AS [IsProcureSuper],
        IsLevyController AS [IsLevyCont],
        IsRecordsManager AS [IsRecordsManager],
        Lup_AP_Product_Bins_ID AS [ProductBins],
        IsBinSuper AS [IsBinSuper],
        IsTillPayout AS [IsTillPayout]
    FROM AW_Users 
    WHERE AW_Users_ID = @User_ID

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

-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Select_IsTillPayout
--Purpose       :Select if POS User is a Till Payout User
--Date          :2017/09/11
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_POS_Select_IsTillPayout]
    (
        @UserID int,
        @IsTillPayout tinyint OUTPUT
    )

AS

SET NOCOUNT ON

    SET @IsTillPayout = 0

    SELECT @IsTillPayout = IsTillPayout
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

	IF @IsTillPayout IS NULL 
        BEGIN	
    		SET @IsTillPayout = 0 
        END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Insert_Multi_Split_GL_Transactions]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Insert_Multi_Split_GL_Transactions]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------
--Description   :sp_AO_Insert_Multi_Split_GL_Transactions
--Purpose       :Inserts Multi-Split Supplier Transactions 
--Functionality :Updates Allocation Split GL Accounts here
--Date          :2003/12/11
--Authors       :TB
--MODS          :
--2004.5.2      :11/07/11 - Fixed @SupplierName = LEFT(Supplier_Name, 30) !!!!
--2015.6.3 RGL  :2017/09/11 - Added Comment to GL Description
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_Multi_Split_GL_Transactions]
    (
        @AO_Header_ID int,
        @AB_Accounts_ID int,
    	@Tax_Method tinyint,
    	@Amount money,
    	@Tax_Code tinyint,
    	@Tax_Amount money,
    	@Net_Amount money,
    	@Comments varchar(50),
    	@GL_Description varchar(50) = '',
    	@User_ID int,
    	@Company_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @Description varchar(200),
            @Suppliers_ID int,
            @SupplierName varchar(30),
            @TranType_ID smallint,
            @Ref_No varchar(20),
            @Document_Date datetime,
            @Months_ID tinyint,
            @Years_ID int,
            @ABTranTypeID tinyint
    
	BEGIN TRANSACTION

    --> Get The Supplier TRANSACTION details of this Transaction
		SELECT @Suppliers_ID = AO_Suppliers_ID,
               @TranType_ID = Sys_AW_Transaction_Types_ID,
               @Document_Date = Document_Date,
               @Months_ID = Slu_AW_Months_ID,
               @Years_ID = Slu_AW_Years_ID,
               @Ref_No = Document_Number
		FROM AO_Transactions
		WHERE AO_Transactions_ID = @AO_Header_ID

		SELECT @SupplierName = LEFT(Supplier_Name, 30)
		FROM AO_Suppliers 
		WHERE AO_Suppliers_ID = @Suppliers_ID

        SET @Description = RTRIM(LTRIM(@SupplierName)) + ' - ' + RTRIM(LTRIM(@GL_Description)) + ' - ' + RTRIM(LTRIM(ISNULL(@Comments,'')))
        SET @Description = LEFT(@Description, 50)


    --> Set Sys_AB_Transaction_Types_ID for GL Trans
        IF @TranType_ID = 9     --9 = Supplier Refund
            SET @ABTranTypeID = 6        --6 = Accounts Payable - Refund
        ELSE                         --8 = Supplier Invoice
            SET @ABTranTypeID = 5        --5 = Accounts Payable - Invoice


		EXEC sp_AB_Insert_GL_Transactions
                @Description,
                @ABTranTypeID,	
                @AB_Accounts_ID,
                @Document_Date,
                @Ref_No,
                @Months_ID,
                @Years_ID,
                @AO_Header_ID,
                @Net_Amount,
                @User_ID,
                @Company_ID	


	COMMIT TRAN
	

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Reverse_Payment_Component_Count]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Reverse_Payment_Component_Count]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AO_Reverse_Payment_Component_Count
--Purpose       :Select COUNT of Supplier Payment Source Transactions components
--Funtionality  :
--Date          :2004/12/16
--Authors       :TB
--MODS          :
--V6.2	RL	2015-04-30	:Allow payment to be reveresed even if it has not been allocated.
--						 I can't see why you would not allow this ?????????
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Reverse_Payment_Component_Count]
    (
        @TranRefNo varchar(20),
        @CompanyID int,
        @TranCount int OUTPUT
    )

AS

SET NOCOUNT ON


    --SELECT @TranCount = count(*)

    --FROM AO_Transactions_Transactions st
    --    LEFT JOIN AO_Transactions t
    --        ON st.Destination_AO_Transactions_ID = t.AO_Transactions_ID
    --    LEFT JOIN AO_Suppliers s
    --        ON t.AO_Suppliers_ID = s.AO_Suppliers_ID
    --    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
    --        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    
    --WHERE st.AW_User_Companies_ID = @CompanyID AND
    --      st.Tran_Ref_No = @TranRefNo AND
    --     (st.Tran_Ref_No <> '' OR
    --      st.Tran_Ref_No IS NULL)

	SELECT @TranCount = 1

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Reverse_Payment_Component_Count]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Reverse_Payment_Component_Count]
GO
------------------------------------------------------------------------------
--Description   :sp_AS_Reverse_Payment_Component_Count
--Purpose       :Select COUNT of Customer Payment Source Transactions components
--Funtionality  :
--Date          :2005/06/07
--Authors       :TB
--MODS          :
--RL	V6.1	:2015-03-13 - Removed the check to see if payment has been allocated
--				 Why would you not be bale to reverse a payment that has not been allocated????
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Reverse_Payment_Component_Count]
    (
        @TranID int,
        @CompanyID int,
        @TranCount int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TranCount = 1

    --SELECT @TranCount = count(*)
    --FROM AS_Transactions_Transactions st
    --    LEFT JOIN AS_Transactions t
    --        ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
    --    LEFT JOIN AC_Customers c
    --        ON t.AC_Customers_ID = c.AC_Customers_ID
    --    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
    --        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    
    --WHERE st.AW_User_Companies_ID = @CompanyID AND
    --      st.Destination_AS_Transactions_ID = @TranID

SET NOCOUNT OFF
GO
--Clean Lup_AS_CBilling_Providers Table
--Select * From Lup_AS_CBilling_Providers
Delete From Lup_AS_CBilling_Providers Where ISNULL(Description,'') = ''
GO
Update Lup_AS_CBilling_Providers
Set Folder = ''
GO

--Bridgestone
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'SQ/Speedy1',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'Br1dge$t0ne',
	Login_Password = '@Br1dge$p1r@1#'
Where LTRIM(RTRIM(ISNULL([Description],''))) IN ('Brigestone1', 'Brigestone', 'Alacrity', 'gatekeeper.alacrity.co.za', 'CBOS')
GO
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'SQ/Speedy1'
)
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
	(
		'SQ/Speedy1',
		'spiralsoft.co.za',
		'Br1dge$t0ne',
		'@Br1dge$p1r@1#',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--Hi-Q
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Hi-Q1',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'HiQss',
	Login_Password = '@H1Q$p1r@1#'
Where LTRIM(RTRIM(ISNULL([Description],''))) IN ('Innovation Group','Hi-Q1')
GO
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Hi-Q1'
)
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
	(
		'Hi-Q1',
		'spiralsoft.co.za',
		'HiQss',
		'@H1Q$p1r@1#',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--Dunlop
--Add Dunlop Rewards Details
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Dunlop1',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'D*nl0p',
	Login_Password = '$D&nl0p$p1r@1@'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Dunlop Rewards'
GO

IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Dunlop1'
)
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
	(
		'Dunlop1',
		'spiralsoft.co.za',
		'D*nl0p',
		'$D&nl0p$p1r@1@',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--TyreMart
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Tyremart1'
)
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
	(
		'Tyremart1',
		'spiralsoft.co.za',
		'Tyr#M@rt',
		'&Tyr#M@rt$17',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO


UPDATE Lup_AS_CBilling_Providers
SET Server_Name = 'spiralsoft.co.za',
	Login_Name = 'Tyr#M@rt',
	Login_Password = '&Tyr#M@rt$17'
WHERE [Description] = 'Tyremart1'
GO

--BestDrive
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'BestDrive'
)
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
	(
		'BestDrive',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

UPDATE Lup_AS_CBilling_Providers
SET Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
WHERE [Description] = 'BestDrive'
GO

--KwikFit
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'KwikFit1'
)
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
	(
		'KwikFit1',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--PointS1
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'PointS1'
)
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
	(
		'PointS1',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

UPDATE Lup_AS_CBilling_Providers
SET Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
WHERE [Description] = 'PointS1'
GO

--Noise Boys
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Noise Boys1'
)
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
	(
		'Noise Boys1',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

UPDATE Lup_AS_CBilling_Providers
SET Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
WHERE [Description] = 'Noise Boys1'
GO

--TyrePlus
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'TyrePlus1'
)
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
	(
		'TyrePlus1',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

UPDATE Lup_AS_CBilling_Providers
SET Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
WHERE [Description] = 'TyrePlus1'
GO

--Deactive Four Fleet
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Four Fleet',
	Server_Name = 'XXX',
	Login_Name = 'XXX',
	Login_Password = 'XXX',
	Slu_AW_Active_ID = 2
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Four Fleet'
GO

--Submission1
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Res1',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Res1'
GO

IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Res1'
)
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
	(
		'Res1',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--Submission2
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Res2',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Res2'
GO

IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Res2'
)
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
	(
		'Res2',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

--Submission3
UPDATE Lup_AS_CBilling_Providers
SET [Description] = 'Res3',
	Server_Name = 'spiralsoft.co.za',
	Login_Name = 'XXX',
	Login_Password = 'XXX'
Where LTRIM(RTRIM(ISNULL([Description],''))) = 'Res3'
GO

IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AS_CBilling_Providers
  WHERE [Description] = 'Res3'
)
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
	(
		'Res3',
		'spiralsoft.co.za',
		'XXX',
		'XXX',
		GETDATE(),
		1,
		1,
		1,
		''
	)
END 
GO

Update Sys_AW_Lookup_Editor
Set Slu_AW_Active_ID = 2
Where TableName = 'Lup_AS_CBilling_Providers'
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description	:sp_AO_GRV_Select_Outstanding_Order_Details
--Purpose       :Fetches Outstanding Order items for an outstanding order
--              :
--Date			:2002/01/13
--Authors		:TB
--MODS          :
--2004.3.5      :29/04/07 - Added Product_Code field and [User] and [Active] JOINS
--V6.3	RL	2017-09-16 - Added product Price_1 to selection
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_GRV_Select_Outstanding_Order_Details]
    (
    	@Orders_ID int
    )

AS

SET NOCOUNT ON

	SELECT OD.AO_Order_Details_ID AS [ID],
        OD.AO_Orders_ID AS [FK ID],
        OD.AP_Products_ID AS [Products ID],
        P.[Description] AS [Product],
        P.Product_Code AS [Code],
        OD.Order_Qty AS [Qty],	
        OD.Free_Qty AS [Free Qty],
        OD.Back_Order_Qty AS [B/O Qty],
        OD.Received_Qty AS [Received Qty],
        OD.Receipt_Date AS [Receipt Date],	
        OD.Unit_Price AS [Unit Price],
        
        OD.Trade_Discount_Formula_ID AS [Trade_Discount_Formula_ID],
        OD.Trade_Discount_Amount AS [Trade Disc],
        OD.Trade_Discount_Percentage AS [Trade Disc Perc],
        OD.Rebate_Formula_ID AS [Rebate_Formula_ID],
        OD.Rebate_Discount_Amount AS [Rebate Disc],
        OD.Rebate_Discount_Percentage AS [Rebate Disc Perc],
        OD.Other_Discount_Formula_ID AS [Other_Discount_Formula_ID],
        OD.Other_Discount_Amount AS [Other Disc],
        OD.Other_Discount_Percentage AS [Other Disc Perc],
        
        OD.Net_Amount AS [Net Amount],
        OD.Sys_AW_Tax_Codes_ID AS [Tax_Codes_ID],
        TC.[Description] AS [Tax Code],
        OD.Tax_Amount AS [Tax],
        OD.Total_Cost AS [Total Cost],
        OD.Lead_Time AS [Lead Time],	
        OD.Date_Captured AS [Date Captured],
        OD.[User_ID] AS [User ID],
        u.UserName AS [User],
        OD.AW_User_Companies_ID AS [Company],
--        OD.Slu_AW_Active_ID AS [Active]
        a.[Description] AS [Active],
        P.On_Hand AS [On Hand],
		dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()) AS [Price 1]
    FROM AO_Order_Details OD
        LEFT JOIN AP_Products P
            ON OD.AP_Products_ID  = P.AP_Products_ID 
        LEFT JOIN Sys_AW_Tax_Codes TC
            ON OD.Sys_AW_Tax_Codes_ID = TC.Sys_AW_Tax_Codes_ID
        LEFT JOIN AW_Users u
            ON OD.[User_ID]  = u.AW_Users_ID
        LEFT JOIN Slu_AW_Active a
            ON OD.Slu_AW_Active_ID = a.Slu_AW_Active_ID

    WHERE OD.AO_Orders_ID = @Orders_ID AND
         (OD.Order_Qty + OD.Back_Order_Qty) > OD.Received_Qty


SET NOCOUNT ON
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Customer_Statement_Allocations]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Customer_Statement_Allocations]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statement_Allocations
--Purpose       :Customer Statement Payments Transaction Allocations
--Date          :2004/05/30
--Authors       :TB
--Version       :1.0.0
--MODS:         :
--V6.3	RL	2017/09/18 - The report should displays when the allocation was done, and not the transaction date
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statement_Allocations]
    (
        @Company_ID int,
        @CustomerID int,
        @PeriodProceduresID int
    )
AS

SET NOCOUNT ON

    DECLARE @ThisPeriodProceduresDate datetime,
            @PrevPeriodProceduresDate datetime

    IF @PeriodProceduresID <> 0
        BEGIN
            SELECT @ThisPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE AW_Period_Procedures_ID = @PeriodProceduresID

        	IF @ThisPeriodProceduresDate IS NULL
                BEGIN
            		SET @ThisPeriodProceduresDate =  getdate()
                    RETURN
                END

            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  Month_End_Date < @ThisPeriodProceduresDate AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC

        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END
        END

    ELSE
        BEGIN
            SELECT Top 1 @PrevPeriodProceduresDate = Month_End_Date
            FROM AW_Period_Procedures 
            WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
                  AW_User_Companies_ID = @Company_ID
            ORDER BY Month_End_Date DESC


        	IF @PrevPeriodProceduresDate IS NULL
                BEGIN
            		SET @PrevPeriodProceduresDate =  '1900/01/01 00:00:01'
                    RETURN
                END

            SET @ThisPeriodProceduresDate = getdate()

        END


    SELECT
        t.AS_Transactions_ID AS [ReceiptID],
        CONVERT(datetime, CONVERT(CHAR(10), t.Transaction_Date, 121)) AS [ReceiptDate], 
        t.Transaction_Number AS [ReceiptNo],
        ISNULL(tt.[Description], '') AS [TranType],
        CONVERT(datetime, CONVERT(CHAR(10), dt.Transaction_Date, 121)) AS [TranDate], 
        dt.Transaction_Number AS [TranNo],
        dt.Total_Amount AS [TranTotal],
        st.Amount AS [Allocated],
        ISNULL(dt.Total_Amount, 0) + ISNULL(dt.Payment_Amount, 0) AS [Balance]

    FROM AS_Transactions t
        INNER JOIN AS_Transactions_Transactions st
            ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
        INNER JOIN AS_Transactions dt
            ON dt.AS_Transactions_ID = st.Source_AS_Transactions_ID
        LEFT JOIN Sys_AW_Transaction_Types tt
             ON dt.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID

    WHERE t.AC_Customers_ID = @CustomerID AND
		(
			--t.Transaction_Date Between @PrevPeriodProceduresDate AND @ThisPeriodProceduresDate 
			-- The report should displays when the allocation was done, and not the transaction date
			--st.Date_Captured Between @PrevPeriodProceduresDate AND @ThisPeriodProceduresDate 
			st.Date_Captured > @PrevPeriodProceduresDate
		) AND

         (t.Sys_AW_Transaction_Types_ID = 7 OR
          t.Sys_AW_Transaction_Types_ID = 21 OR
          t.Sys_AW_Transaction_Types_ID = 22) 

    ORDER BY t.Date_Captured

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_ASTD]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_ASTD]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   : Selects the Transaction Details for Dynamic reports
--Purpose       : Dynamic SQL statements have a 8,000 character limit
--Functionality : Overcome 8,000 character limit
--Parameters    : 
--Date          : 2017/06/19
--Authors       : RL
--Version       : 1
-------------------------------------------------------------------------------
CREATE     VIEW [dbo].[vw_ASTD]

AS

    SELECT *
    FROM AS_Transaction_Details
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Customer_Statements]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statements
--Purpose       :Retrieves Customer Statement data in Statements Report
--Tables        :AC_Statements, AC_Statement_Details
--Functionality :Prints only Customers with transactions owing
--Date          :2002/06/14
--Authors       :TB
--Version       :1.0.0
--MODS          :24/06/02 - Changed ORDER BY from CustomerID to t.FullName
--              :09/08/02 - Modified ORDER BY to include TransactionDate
--              :19/05/03 - Modified formatting CONVERT(int, d.Transaction_Date)
--              :           that ROUNDS THE DATE UP after 12:00 midday !!!!!!!,
--              :           to CONVERT(CHAR(10), d.Transaction_Date, 121)) that truncates
--              :02/11/04 - Trimmed Transaction_Number and Comment fields
--              :17/05/05 - Reworked ORDER BY to force grouping one customer's
--              :           transactions together when DUPLICATE CUSTOMER NAMES exist
--2004.3.5      :22/05/07 - Added [TransactionNo] in the SORT ORDER
--              :22/05/07 - Added [CreditTerms] field
--              :22/05/07 - Added [TermsType] field
--              :15/06/07 - Added OrderNo and OrderNotes fields
--2004.4.2      :01/11/08 - Commented in WHERE clause to include transactions
--              :           that have ZERO owing amounts
--V6.3	RL	2017-09-18 - Added option to pull report for specific customer
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements]
    (
        @PeriodProceduresID	int,
		@CustomerID			int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

IF @CustomerID = 0
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END
ELSE
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements t 
			INNER JOIN AC_Statement_Details d
				ON t.AC_Statements_ID = d.AC_Statements_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AC_Customer_Statements_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements_Temp]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_RPT_AC_Customer_Statements_Temp
--Purpose       :Retrieves Ad-Hoc Customer Statement data in Statements Report
--Tables        :AC_Statements_Temp, AC_Statement_Details_Temp
--Functionality :Prints only Customers with transactions owing
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :24/06/02 - Changed ORDER BY from CustomerID to t.FullName
--              :09/08/02 - Modified ORDER BY to include TransactionDate
--              :19/05/03 - Modified formatting CONVERT(int, d.Transaction_Date)
--              :           that ROUNDS THE DATE UP after 12:00 midday !!!!!!!,
--              :           to CONVERT(CHAR(10), d.Transaction_Date, 121)) that truncates
--              :02/11/04 - Trimmed Transaction_Number and Comment fields
--              :17/05/05 - Reworked ORDER BY to force grouping one customer's
--              :           transactions together when DUPLICATE CUSTOMER NAMES exist
--2004.3.5      :22/05/07 - Added ORDER BY clause and [TransactionNo] in the SORT ORDER
--              :22/05/07 - Added [CreditTerms] field
--              :22/05/07 - Added [TermsType] field
--              :15/06/07 - Added OrderNo and OrderNotes fields
--2004.4.2      :01/11/08 - Commented in WHERE clause to include transactions
--              :           that have ZERO owing amounts
--V6.3	RL	2017-09-18 - Added option to pull report for specific customer
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AC_Customer_Statements_Temp]
    (
        @PeriodProceduresID int,
		@CustomerID			int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

IF @CustomerID = 0
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END
ELSE
BEGIN
	IF @ShowZeroBalance = 0
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND t.Account_Balance <> 0 --@ShowZeroBalance = 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
	ELSE
	BEGIN
		SELECT 
			CONVERT(datetime, CONVERT(CHAR(10), d.Transaction_Date, 121)) AS [TransactionDate], 
			tt.[Description] AS [Type], 
			RTRIM(LTRIM(d.Transaction_Number)) AS [TransactionNo], 
			ISNULL(d.Amount, 0) AS [Amount], 
			ISNULL(d.Payment, 0) AS [Payment], 
			ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) AS [Balance], 
			t.AC_Customers_ID AS [CustomerID], 
			t.FullName AS [Customer],
			ISNULL(t.Customer_Number, '') + ' (' + CONVERT(VARCHAR(12), t.AC_Customers_ID) + ')' AS [CustomerNo],
			t.Post_Address AS [CustomerPostAddress],
			t.Post_Office AS [CustomerPostOffice],
			t.Post_Code AS [CustomerPostCode],
			ISNULL(ct.[Description], '') + ISNULL(' ' + ctt.[Description], '') AS [CreditTerms],
			t.Work_Email AS [CustomerEmail],
			t.Account_Balance AS [AccountBalance],    -- now SUM(Ageing)
			t.[Current],
			t.[30Days],
			t.[60Days],
			t.[90Days],
			(ISNULL(t.[120Days], 0) +
			 ISNULL(t.[150Days], 0) +
			 ISNULL(t.[180+Days], 0)) AS [120+Days],
			RTRIM(LTRIM(z.Comment)) AS [Notes],
			RTRIM(LTRIM(z.Customer_Reference)) AS [OrderNo],
			RTRIM(LTRIM(ISNULL(z.Customer_Reference, '') + ISNULL(' ' + z.Comment, ''))) AS [OrderNotes]
		FROM AC_Statements_Temp t 
			LEFT JOIN AC_Statement_Details_Temp d
				ON t.AC_Statements_Temp_ID = d.AC_Statements_Temp_ID
			INNER JOIN AC_Customers c
				ON t.AC_Customers_ID = c.AC_Customers_ID
			LEFT JOIN Slu_AW_Credit_Terms ct
				ON c.Slu_AW_Credit_Terms_ID = ct.Slu_AW_Credit_Terms_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 OUTER JOIN Sys_AW_Transaction_Types tt
				ON d.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
			LEFT JOIN AS_Transactions z
				ON z.Sys_AW_Transaction_Types_ID = d.Sys_AW_Transaction_Types_ID AND
				   z.Transaction_Date = d.Transaction_Date AND
				   z.Transaction_Number = d.Transaction_Number
		WHERE t.AW_Period_Procedures_ID = @PeriodProceduresID             --AND
	--          ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			AND c.AC_Customers_ID = @CustomerID	--@CustomerID
		ORDER BY t.FullName, [CustomerNo], [TransactionDate], [TransactionNo]
	END
END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Customer_Statements_Temp_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Customer_Statements_Temp_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Customer_Statements_Temp_Insert
--Purpose       :Saves an Ad-Hoc snapshot of Account Customer Transactions
--              :between month-end Period Procedures 
--Functionality :ONLY Customers that have had transactions are selected
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Version       :1.0.0
--MODS          :07/08/02 - Clear the Ageing Balances BEFORE NEXT FETCH
--              :09/08/02 - Replaced @Now with (renamed @Date to @DatePicked)
--              :16/08/02 - Added Sys_AW_Transaction_Types_ID = 21 & 22 from
--              :               21=Back Office Receipt, 22=EFT Receipt
--              :10/11/02 - Validate NULL Total_Amount & Payment_Amount in WHERE clauses
--              :           to return transactions inserted with NULL Total_Amount
--              :27/01/03 - Modified @DatePicked to reflect date and ending time
--              :           as at 12 midnight of the date of @DatePicked
--              :15/09/03 - Added @CompanyID in WHERE clause of Customer_Cursor
--              :22/09/03 - Added @CompanyID filter to sp_AW_Period_Procedures_Select
--2004.3.2      :13/09/06 - Added update Date_Captured as @Date in AC_Statements_Temp
--              :           and AC_Statement_Details_Temp
--2004.4.2      :01/11/08 - Modified WHERE clause to include CURRENT MONTH transactions
--              :           that have ZERO owing from LAST MONTH-END to @DatePicked
--              :02/11/08 - Added insert validation if Customer @HasBalance or zero balance
--              :           with non-zero ageing
--V6.2	RL	2016-03-30 - Moved Filter to cursor select for speed performance
--V6.2	RL	2016-03-30 - Removed balance <> 0 check. This prevented paid up accounts from displaying for the current month
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Customer_Statements_Temp_Insert]
	(
        @DatePicked			DateTime,
		@CustomerID_Single	int,
		@ShowZeroBalance	int, 
        @CompanyID			int,
        @UserID				int
	)

AS

SET NOCOUNT ON

	DECLARE
        @LastPeriodProcedureDate DateTime,
        @PeriodProcedureID int,
        @CustomerID int,
        @CustomerName varchar(90),
        @CustomerNumber varchar(10),
        @PostBox varchar(20),
        @PostOffice varchar(30),
        @PostCode varchar(10),
        @WorkEmail varchar(40),
        @AccountBalance money,
        @StatementID int,
        @Now datetime,
        @D1 dateTime,
        @D2 datetime,
        @D3 datetime,
        @D4 datetime,
        @D5 datetime,
        @D6 datetime,
        @D7 datetime,
        @AgePayment money,
        @AgeAmount money,
        @AgeCurrent money,
        @Age30Days money,
        @Age60Days money,
        @Age90Days money,
        @Age120Days money,
        @Age150Days money,
        @Age180Days money,
        @HasBalance tinyint,
		@ZeroBalance money

--	SET @DatePicked = getdate()  --REMOVE THIS: Selected in Statement Print datepicker

--	SET @Now = @DatePicked

--> (27/01/03) Truncates the decimal of today's date e.g.
--        '2002-09-24 13:33:45.076' as '2002-09-24 00:00:00.000',
--        and adds 1 day which equals midnite tonight
--        which returns '2002-09-25 00:00:00.000'
    SET @Now = CONVERT(datetime, DATEADD(dd, 1, ROUND(CONVERT(float, @DatePicked), 0, 1)))

    SET @DatePicked = @Now

    SET @PeriodProcedureID = 0
    SET @HasBalance = 0

--------------------------
-- 	SET @CompanyID = 1
-- 	SET @UserID = 2
--------------------------

--Wipe the TEMP table-------
    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statement_Details_Temp]
        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AC_Statements_Temp]
        
        CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
        	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AC_Statements_Temp_ID] [int] NULL ,
        	[Transaction_Date] [datetime] NULL ,
        	[Sys_AW_Transaction_Types_ID] [int] NULL ,
        	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL 
        ) ON [PRIMARY]
        
        CREATE TABLE [dbo].[AC_Statements_Temp] (
        	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AW_Period_Procedures_ID] [int] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Amount] [money] NULL ,
        	[Payment] [money] NULL ,
        	[Account_Balance] [money] NULL ,
        	[Current] [money] NULL ,
        	[30Days] [money] NULL ,
        	[60Days] [money] NULL ,
        	[90Days] [money] NULL ,
        	[120Days] [money] NULL ,
        	[150Days] [money] NULL ,
        	[180+Days] [money] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL 
        ) ON [PRIMARY]
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'

        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
        
        setuser
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'
        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]'

        setuser

    END
----------------------------

    BEGIN
    --> Step 1: Get the date of the LAST Month-End done
    	SELECT TOP 1 @LastPeriodProcedureDate = Month_End_Date 
    	FROM AW_Period_Procedures 
    	WHERE Sys_AW_Period_Procedure_Types_ID = 1 
    	ORDER BY Month_End_Date DESC
    
        --> Initialize M/E date if this is the FIRST Month-End procedure
    	IF @LastPeriodProcedureDate IS NULL 
    		SET @LastPeriodProcedureDate = '1900/01/01'
   
    --> Step 3: Get the last 7 Month-End dates to insert ageing for each Account
        EXEC sp_AW_Period_Procedures_Select
                @DatePicked,
                @D1 OUTPUT,
                @D2 OUTPUT,
                @D3 OUTPUT,
                @D4 OUTPUT,
                @D5 OUTPUT,
                @D6 OUTPUT,
                @D7 OUTPUT,
                1,
                @CompanyID
   
		IF @CustomerID_Single = 0
		BEGIN
			IF @ShowZeroBalance = 0
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers @CustomerID_Single = 0 And @ShowZeroBalance = 0
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0))
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE c.AW_User_Companies_ID = @CompanyID AND
							(
								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
							 ) OR
							 ( t.Transaction_Date > @D1 )		--All new transactions
						GROUP BY c.AC_Customers_ID,
								ISNULL(c.Surname, '') +
								ISNULL(', ' + c.FirstNames, ''),
								ISNULL(c.Post_Box, ''),
								ISNULL(c.Post_Office, ''),
								ISNULL(c.Post_Code, ''),
								ISNULL(c.Work_Email, ''),
								ISNULL(c.Customer_Number, '')
						HAVING SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)) <> 0
					)
			END
			ELSE
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single = 0 And @ShowZeroBalance = 1
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							0
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE c.AW_User_Companies_ID = @CompanyID AND
							(
								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
							 ) AND
							 (
								ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0) <> 0 OR     --If there are not transactions after the last month end, you should still return customers with a balance
								t.Transaction_Date > @D1		--All new transactions
							  )
                
					)
			END
		END
		ELSE
		BEGIN
			IF @ShowZeroBalance = 0
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single <> 0 And @ShowZeroBalance = 0
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0))
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
							INNER JOIN AS_Transactions t
								ON c.AC_Customers_ID = t.AC_Customers_ID
						 WHERE	c.AW_User_Companies_ID = @CompanyID AND
								c.AC_Customers_ID = @CustomerID_Single AND
							(
								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
							 ) OR
							 ( t.Transaction_Date > @D1 )		--All new transactions
						GROUP BY c.AC_Customers_ID,
								ISNULL(c.Surname, '') +
								ISNULL(', ' + c.FirstNames, ''),
								ISNULL(c.Post_Box, ''),
								ISNULL(c.Post_Office, ''),
								ISNULL(c.Post_Code, ''),
								ISNULL(c.Work_Email, ''),
								ISNULL(c.Customer_Number, '')
						HAVING SUM(ISNULL(t.Total_Amount, 0) + ISNULL(t.Payment_Amount, 0)) <> 0
					)
			END
			ELSE
			BEGIN
			--> Step 4: Define a CURSOR for AC_Customers AC_Customers @CustomerID_Single <> 0 Show all, even if no transaction for month
       			DECLARE Customer_Temp_Cursor CURSOR FOR
					(
						SELECT DISTINCT
							c.AC_Customers_ID,
							ISNULL(c.Surname, '') +
							ISNULL(', ' + c.FirstNames, '') AS [FullName],
							ISNULL(c.Post_Box, ''),
							ISNULL(c.Post_Office, ''),
							ISNULL(c.Post_Code, ''),
							ISNULL(c.Work_Email, ''),
							ISNULL(c.Customer_Number, ''),
							0
						--V6.3 Added filter here to improve speed	
						--> Show ALL TRANSACTIONS NON-ZERO owing
						 FROM AC_Customers c
						WHERE c.AW_User_Companies_ID = @CompanyID AND
							c.AC_Customers_ID = @CustomerID_Single
                
					)
			END
		END
    
    	OPEN Customer_Temp_Cursor
    
        	FETCH NEXT FROM Customer_Temp_Cursor 
        	INTO
                @CustomerID,
                @CustomerName,
                @PostBox,
                @PostOffice,
                @PostCode,
                @WorkEmail,
                @CustomerNumber,
				@ZeroBalance
        	
        	WHILE @@FETCH_STATUS = 0
        	BEGIN
    
        		SELECT
                    @AgePayment = Payment,
                    @AgeAmount = Amount,
                    @AgeCurrent = [Current],
                    @Age30Days = [30 Days],
                    @Age60Days = [60 Days],
                    @Age90Days = [90 Days],
                    @Age120Days = [120 Days],
                    @Age150Days = [150 Days],
                    @Age180Days = [180+ Days]
        		FROM dbo.fn_AC_Customer_Ageing_Values
                    (
                        @CustomerID,
                        @DatePicked,
                        @D1,
                        @D2,
                        @D3,
                        @D4,
                        @D5,
                        @D6,
                        @D7
                    )

                SET @AccountBalance = @AgeCurrent + 
                                      @Age30Days + 
                                      @Age60Days + 
                                      @Age90Days + 
                                      @Age120Days + 
                                      @Age150Days + 
                                      @Age180Days

                --> 2004.4.2
                --SET @HasBalance = 0
                
                --V6.2 Already did filtering in cursor select
                --If you check for balance here you will miss paid up accounts for this month
                SET @HasBalance = 1

                --IF @AccountBalance <> 0
                --    BEGIN
                --        SET @HasBalance = 1
                --    END

                --IF @HasBalance = 0
                --    BEGIN
                --        IF @AgeCurrent <> 0 OR
                --            @Age30Days <> 0 OR
                --            @Age60Days <> 0 OR
                --            @Age90Days <> 0 OR
                --            @Age120Days <> 0 OR
                --            @Age150Days <> 0 OR
                --            @Age180Days <> 0
                --            BEGIN
                --                SET @HasBalance = 1
                --            END
                --    END
                    
                IF @HasBalance = 1
                    BEGIN
                		INSERT INTO AC_Statements_Temp
                			(
                                AW_Period_Procedures_ID,
                                AC_Customers_ID,
                                FullName,
                                Customer_Number,
                                Post_Address,
                                Post_Office,
                                Post_Code,
                                Work_Email,
                                [User_ID],
                                AW_User_Companies_ID,
                                Amount,
                                Payment,
                                Account_Balance,
                                [Current],
                                [30Days],
                                [60Days],
                                [90Days],
                                [120Days],
                                [150Days],
                                [180+Days],
                                Date_Captured
                            )
                		VALUES
                			(
                                @PeriodProcedureID,    --initialized to 0 ??
                                @CustomerID,
                                rtrim(ltrim(@CustomerName)),
                                @CustomerNumber,
                                @PostBox,
                                @PostOffice,
                                @PostCode,
                                @WorkEmail,
                                @UserID,
                                @CompanyID,
                                @AgeAmount,
                                @AgePayment,
                                @AccountBalance,
                                @AgeCurrent,
                                @Age30Days,
                                @Age60Days,
                                @Age90Days,
                                @Age120Days,
                                @Age150Days,
                                @Age180Days,
                                @DatePicked
                            )
            
                	  	SELECT @StatementID = Scope_Identity()
                
                		--Insert Transactions since LAST Period Procedure Date
                		INSERT INTO AC_Statement_Details_Temp
                			(
                                AC_Statements_Temp_ID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Amount,
                                Payment,
                                Date_Captured,
                                [User_ID],
                                AW_User_Companies_ID
                            )
                        SELECT 
                                @StatementID,
                                Transaction_Date,
                                Sys_AW_Transaction_Types_ID,
                                Transaction_Number,
                                Total_Amount,
                                Payment_Amount,
                                @DatePicked,
                                [User_ID],
                                AW_User_Companies_ID
                        FROM AS_Transactions
                        --> Show ALL TRANSACTIONS NON-ZERO owing
                        WHERE AC_Customers_ID = @CustomerID AND
							(
								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
							) AND
							(
								ISNULL(Total_Amount, 0) + ISNULL(Payment_Amount, 0) <> 0 OR
								Transaction_Date Between @D1 AND @DatePicked 	--All new transactions
							)
                END
            --> 2004.4.2


            --> Clear the Ageing Balances of THIS Customer
            --> In the event that the next Customers has ZERO ageing
                SET @AgePayment = 0
                SET @AgeAmount = 0
                SET @AgeCurrent = 0
                SET @Age30Days = 0
                SET @Age60Days = 0
                SET @Age90Days = 0
                SET @Age120Days = 0
                SET @Age150Days = 0
                SET @Age180Days = 0

            	FETCH NEXT FROM Customer_Temp_Cursor 
            	INTO
                    @CustomerID,
                    @CustomerName,
                    @PostBox,
                    @PostOffice,
                    @PostCode,
                    @WorkEmail,
                    @CustomerNumber,
					@ZeroBalance
    
        	END
    	
    	CLOSE Customer_Temp_Cursor
    
    	DEALLOCATE Customer_Temp_Cursor

    END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Select_Email_Statement_Customers]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Select_Email_Statement_Customers]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AC_Select_Email_Statement_Customers
--Purpose       :Returns all Customers in AC_Statements
--Functionality :
--Parameters    :
--Date          :2004/01/18
--Authors       :TB
--MODS          :19/06/04 - Changed Orders_URL to be the Accounts E-mail address 
--              :21/06/04 - Added [StatementID] field
--2004.3.4      :08/01/07 - Added Customer Surname and Firstname CASE statement
--2004.5.2      :03/06/11 - Added new AW_YesNo_Attach_Tran_ID AS [Attach Docs]
--V6.3	RL	2017-09-18 - Added option to ignore zero balance statements. 
--						 Month end are now pulled for all customers with transactions for a specific month
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AC_Select_Email_Statement_Customers]
    (
        @PeriodProceduresID int,
		@ShowZeroBalance	int
    )

AS

SET NOCOUNT ON

	IF @ShowZeroBalance = 0
	BEGIN
        SELECT DISTINCT
            s.AC_Statements_ID AS [StatementID],
            c.AC_Customers_ID AS [CustomerID], 
            c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
            c.AW_YesNo_Attach_Tran_ID AS [Attach Docs],

            CASE WHEN c.Firstnames IS NULL
                THEN ISNULL(c.Surname, '')
                ELSE ISNULL(c.Surname, '') + ', ' + 
                     LTRIM(ISNULL(c.Firstnames, ''))
                END AS [Customer],

    		c.Customer_Number AS [Customer No],
            c.Orders_URL AS [E-Mail Address],
            c.Post_Box AS [Postal Address],
            c.Post_Office AS [Post Office],
            c.Post_Code AS [Post Code],
            s.Account_Balance AS [Balance]
        FROM AC_Statements s
            INNER JOIN AC_Statement_Details d
                ON s.AC_Statements_ID = d.AC_Statements_ID
            INNER JOIN AC_Customers c
                On s.AC_Customers_ID = c.AC_Customers_ID
        WHERE AW_Period_Procedures_ID = @PeriodProceduresID AND
              --ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
			  s.Account_Balance <> 0
        ORDER BY [Customer]
	END
	ELSE
	BEGIN
        SELECT DISTINCT
            s.AC_Statements_ID AS [StatementID],
            c.AC_Customers_ID AS [CustomerID], 
            c.AW_YesNo_Send_Email_ID AS [Send E-Mail],
            c.AW_YesNo_Attach_Tran_ID AS [Attach Docs],

            CASE WHEN c.Firstnames IS NULL
                THEN ISNULL(c.Surname, '')
                ELSE ISNULL(c.Surname, '') + ', ' + 
                     LTRIM(ISNULL(c.Firstnames, ''))
                END AS [Customer],

    		c.Customer_Number AS [Customer No],
            c.Orders_URL AS [E-Mail Address],
            c.Post_Box AS [Postal Address],
            c.Post_Office AS [Post Office],
            c.Post_Code AS [Post Code],
            s.Account_Balance AS [Balance]
        FROM AC_Statements s
            INNER JOIN AC_Statement_Details d
                ON s.AC_Statements_ID = d.AC_Statements_ID
            INNER JOIN AC_Customers c
                On s.AC_Customers_ID = c.AC_Customers_ID
        WHERE AW_Period_Procedures_ID = @PeriodProceduresID 
              --ISNULL(d.Amount, 0) + ISNULL(d.Payment, 0) <> 0
        ORDER BY [Customer]
	END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_GRV]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_GRV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV
--Functionality :Stock Receipts  
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--MODS			:08/09/04 - Removed GRV History Search date conversion to float
--2004.4.5      :30/05/09 - Added field [GRV No] to display in Stock Receipts History
--V6.3	RL		:2017/09/19 :Added Order By Date_Received descending
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_GRV]
    (
    	@Option tinyint,
    	@CompanyID int,
    	@FromDate datetime = NULL,
    	@ToDate datetime = NULL ,
    	@SupplierID int = NULL
    )

AS

SET NOCOUNT ON

BEGIN

	IF @Option = 0        -- 0 = All GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE Sys_AW_Transaction_Types_ID = 19 AND  --19 = GRV
              AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received DESC

	ELSE
	IF @Option = 1        -- 1 = Only Uninvoiced GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE  Sys_AW_Transaction_Types_ID = 19 AND  --19 = GRV
			AO_GRV_ID NOT IN
                       (SELECT AO_GRV_ID
                        FROM AO_Purchase_Transactions) AND
			AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received DESC

	IF @Option = 2        -- 2 = GRV History
		SELECT AO_GRV_ID AS [ID],
			AO_Suppliers_ID AS [SupplierID],
			AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [GRV No],
			Date_Received AS [Date Received],
			Delivery_Note_Number AS [Delivery Note],
			Supplier_Reference AS [Supplier Reference],
			Trade_Discount_Total AS [Trade Disc],
			Rebate_Discount_Total AS [Rebate Disc],
			Other_Discount_Total AS [Other Disc],
			Net_Amount AS [Net Amount],
			Total_Tax_Amount AS [Tax Total],
			Total_Amount AS [Total]
		FROM AO_GRV
        WHERE Date_Received >= @FromDate AND
              Date_Received <= @ToDate AND
              AO_Suppliers_ID = @SupplierID AND
              AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID IN (19,20)
		ORDER BY Date_Received DESC


END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_CRV]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_CRV]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
--Description   :sp_AO_Select_CRV
--Functionality :Consingment Receipts  
--Parameters    :
--Date          :2002/03/27
--Authors       :TB
--MODS			:08/09/04 - Removed GRV History Search date conversion to float
--2004.4.5      :30/05/09 - Added field [GRV No] to display in Stock Receipts History
--V6.3	RL		:2017/09/19 :Added Order By Date_Received descending
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_CRV]
    (
    	@Option tinyint,
    	@CompanyID int,
    	@FromDate datetime = NULL,
    	@ToDate datetime = NULL ,
    	@SupplierID int = NULL
    )

AS

SET NOCOUNT ON

BEGIN

	IF @Option = 0        -- 0 = All CRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE Sys_AW_Transaction_Types_ID = 31 AND  --31 = CRV
              AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received Desc

	ELSE
	IF @Option = 1        -- 1 = Only Uninvoiced GRV's
		SELECT
            AO_GRV_ID AS [ID],
            AO_Suppliers_ID AS [SupplierID],
            AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
            Date_Received AS [Date Received],
            Delivery_Note_Number AS [Delivery Note],
            Supplier_Reference AS [Supplier Reference],
            Trade_Discount_Total AS [Trade Disc],
            Rebate_Discount_Total AS [Rebate Disc],
            Other_Discount_Total AS [Other Disc],
            Net_Amount AS [Net Amount],
            Total_Tax_Amount AS [Tax Total],
            Total_Amount AS [Total]
		FROM AO_GRV
		WHERE  Sys_AW_Transaction_Types_ID = 31 AND  --19 = GRV
			AO_GRV_ID NOT IN
                       (SELECT AO_GRV_ID
                        FROM AO_Purchase_Transactions) AND
			AW_User_Companies_ID = @CompanyID
		ORDER BY Date_Received Desc

	IF @Option = 2        -- 2 = CRV History
		SELECT AO_GRV_ID AS [ID],
			AO_Suppliers_ID AS [SupplierID],
			AO_Orders_ID AS [Order ID],
            AO_GRV_ID AS [CRV No],
			Date_Received AS [Date Received],
			Delivery_Note_Number AS [Delivery Note],
			Supplier_Reference AS [Supplier Reference],
			Trade_Discount_Total AS [Trade Disc],
			Rebate_Discount_Total AS [Rebate Disc],
			Other_Discount_Total AS [Other Disc],
			Net_Amount AS [Net Amount],
			Total_Tax_Amount AS [Tax Total],
			Total_Amount AS [Total]
		FROM AO_GRV
        WHERE Date_Received >= @FromDate AND
              Date_Received <= @ToDate AND
              AO_Suppliers_ID = @SupplierID AND
              AW_User_Companies_ID = @CompanyID AND
              Sys_AW_Transaction_Types_ID IN (31,32)
		ORDER BY Date_Received Desc


END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_GRV_Report_Data]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_GRV_Report_Data]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------
--Description   :sp_AO_Select_GRV_Report_Data
--Purpose       :Returns GRV data for the GRV Report
--Parameters    :	
--Date          :2002/02/12
--Authors       :TB
--Version       :1.0.0
--Mods		    :22/04/02 - Inserted h.Sys_AW_Transaction_Types_ID AS [TranTypeID]
--              :           to enable printing a Goods Returned Voucher
--              :24/10/04 - Added AO_GRV_ID as [GRVID]
--              :11/05/05 - Added Received/Returned Ny as [Username]
--2004.2.5      :28/11/05 - Changed [SubTotal] field to use Net_Amount column
--2004.3.5      :05/04/07 - Changed [Co Name] to include Company_Name as primary
--V6.3	RL	2017/09/19	:Returned noted for sales order replinishment
----------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Select_GRV_Report_Data]
    (
    	@GRV_ID int
    )

AS

SET NOCOUNT ON

    DECLARE @SuppliersID int,
    		@CompanyID int,
            @OrdersID int,
            @OrderNumber varchar(20),
            @OurOrderRef varchar(20)

BEGIN
	
	SELECT @SuppliersID = AO_Suppliers_ID ,
		   @CompanyID = AW_User_Companies_ID ,
           @OrdersID = AO_Orders_ID
	FROM AO_GRV
	WHERE AO_GRV_ID = @GRV_ID

    IF @OrdersID > 0
        BEGIN
            SELECT @OrderNumber = Order_Number,
                   @OurOrderRef = Our_Ref
            FROM AO_Orders
            WHERE AO_Orders_ID = @OrdersID

            SET @OrderNumber = @OrderNumber + ' (' +
                               CONVERT(VARCHAR(10),@OrdersID) + ')'

        END
    ELSE
        BEGIN
            SET @OrderNumber = ''
            SET @OurOrderRef = ''
        END
	
	SELECT
        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],
--        c.Company_Trading_Name AS [Co Name],
        ISNULL(c.Company_Name, '') + ISNULL(', ' + c.Company_Trading_Name, '') AS [Co Name],
        c.Company_Registration_Number AS [Co RegNo],
        c.Company_Addr1 AS [Co Address1],
        c.Company_Addr2 AS [Co Address2],
        c.Company_Post_Code	AS [Co PostCode],
        c.Tel_No AS [Co TelNo],
        c.Fax_No AS [Co FaxNo],
        c.TAX_Number AS [Co TaxNo],
        h.Date_Received AS [Date Received],
        @OrderNumber AS [Order Number],
        @OurOrderRef AS [Our Ref],
        h.Delivery_Note_Number AS [Del Note Number],
        h.Supplier_Reference AS [Supp Ref],
    --> From GRV Details
        d.AO_GRV_Details_ID AS [ID],
        p.Product_Code AS [Product Code],
        p.[Description] AS [Product Desc],
        d.Qty AS [QTY],
        d.Unit_Price AS [Unit Price],
        d.Trade_Discount_Amount AS [Trade Disc],
        d.Rebate_Discount_Amount AS [Rebate Disc],
        d.Other_Discount_Amount AS [Other Disc],	

--      ((d.Qty * d.Unit_Price) - d.Trade_Discount_Amount - d.Rebate_Discount_Amount - d.Other_Discount_Amount) AS [SubTotal],
        d.Net_Amount AS [SubTotal],

        d.Tax_Amount AS [Tax Amount],
        d.Total_Cost AS [Total Cost],
        h.Sys_AW_Transaction_Types_ID AS [TranTypeID],
        h.AO_GRV_ID AS [GRVID],
        ISNULL(u.Firstname, '' + ' ') + ISNULL(u.Surname, '') AS [Username],
		ISNULL(h.Notes,'') AS [Notes]

	FROM AO_GRV h
        LEFT JOIN AO_Suppliers s
			ON h.AO_Suppliers_ID = s.AO_Suppliers_ID 
		LEFT JOIN AW_User_Companies c 
			ON h.AW_User_Companies_ID = c.AW_User_Companies_ID
		LEFT JOIN AW_Users u 
			ON h.[User_ID] = u.AW_Users_ID
		INNER JOIN AO_GRV_Details d
			ON h.AO_GRV_ID = d.AO_GRV_ID 
		INNER JOIN AP_Products p 
			ON d.AP_Products_ID = p.AP_Products_ID
	WHERE h.AO_GRV_ID = @GRV_ID

END

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Insert_OR_Update_CRV_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Insert_OR_Update_CRV_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
--Description   :sp_AO_Insert_OR_Update_CRV_Detail
--Purpose       :Inserts Consignemnt CRV Detail and Updates On_Hand
--Functionality :
--Parameters    :
--Date          :2015/03/27
--Authors       :TB
--Version       :6.0.2
--V6.3	RL		:2017-04-21 :Added check to fill back orders
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Insert_OR_Update_CRV_Detail]
    (	
    	@AO_Order_Details_ID int = 0,
    	@AO_GRV_ID int,
    	@AP_Products_ID int,
    	@Qty decimal(9,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

SET NOCOUNT ON

	DECLARE @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),
            @New_Last_Cost money,
            @New_On_Hand Decimal(9,3),
    		@Orders_ID Int,
    		@Received_Qty Decimal(19,3),
    		@Count1 int,
    		@Count2 int,
    		@Net_Purchase_Price money,
    		@Note varchar(70),
    		@User_Name varchar(40),
        --> GL variables for Supplier GL Detail
    		@Use_Rebate_Disc_GL_Acc Bit,
    		@Use_Other_Disc_GL_Acc Bit,
    		@Rebate_Disc_GL_Acc int,
    		@Other_Disc_GL_Acc int,
    		@Purchases_Contol_Acc_ID int,
    		@Suppliers_ID int,
			@chkSOAutoReplenishBO_GRV	varchar(10)

    BEGIN
    	BEGIN
    		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,
        			Qty_Returned,
        			Qty_Sold,
        			Qty_Left
                )
    		VALUES
                (
                    @AO_GRV_ID ,
        			@AP_Products_ID ,
        			@Qty ,
        			@Unit_Last_Cost ,
        			@TradeDisc ,
        			@RebateDisc ,
        			@OtherDisc ,
        			@NetAmount ,
        			@Tax_Code_ID ,
        			@TaxAmount ,
        			@TotalCost ,
        			@UserID ,
        			@CompanyID,
        			0,
        			0,
        			@Qty
                )
    	END
    	
    	BEGIN	
            SELECT @Prev_On_Hand = ISNULL(On_Hand, 0) ,
                   @Prev_Last_Cost = ISNULL(Last_Cost, 0) ,
                   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0) ,
                   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0) ,
                   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0)
    		FROM AP_Products
    		WHERE AP_Products_ID = @AP_Products_ID
    
    		SET @New_On_Hand = @Prev_On_Hand + @Qty    --New On_Hand Qty
      
      
--> CALCULATE NEW LAST COST ----------------------------------------------

            SET @Net_Purchase_Price = ISNULL(@Unit_Last_Cost, 0) * ISNULL(@Qty, 1)
      
		UPDATE AP_Products
        SET On_Hand = @Prev_On_Hand + @Qty,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @AP_Products_ID      
		
		--V6.2 Update Bin Qty
		IF @Qty <> 0
		BEGIN
			--SELECT @Oppisite_Qty = @Quantity * -1
			
			EXEC sp_AP_Products_Bins_Update_Insert 
			@AP_Products_ID,--@ProductID int,
			1,--@ProductBinID int,
			@Qty,--@Qty decimal(9,3)
			'CRV',--@Source varchar(10),
			0,--@Batch_No
			@UserID,--@UserID int,
			@CompanyID--@CompanyID int			    	
		END	
		
      
		END
            
    		--BEGIN
    		--	SELECT @Suppliers_ID = AO_Suppliers_ID
    		--	FROM AO_GRV
    		--	WHERE AO_GRV_ID = @AO_GRV_ID
    		
    		--	SELECT  @Use_Rebate_Disc_GL_Acc = Use_Rebate_Discount_Control_Acc,
    		--			@Use_Other_Disc_GL_Acc = Use_Other_Discount_Control_Acc,
    		--			@Rebate_Disc_GL_Acc = AB_Rebate_Discount_Account_ID,
    		--			@Other_Disc_GL_Acc = AB_Other_Discounts_Account_ID
    		--	FROM AO_Suppliers 
    		--	WHERE AO_Suppliers_ID = @Suppliers_ID
    	
    		--	SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    		--	FROM AB_Control_Accounts
    		--	WHERE Control_Number = 301    --Purchases
    		--END


        --> Update Purchase with Net Acquisition Cost
--            IF @Use_Rebate_Disc_GL_Acc = 1    -- 1 = YES
--				BEGIN
--					IF @Rebate_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
--                        --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
--					ELSE
--                        --> Last_Cost = UnitPrice - (Trade)
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@TradeDisc, 0)
--				END

--        --> @Use_Rebate_Disc_GL_Acc = 0    -- 0 = NO
--			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate) = Net Acquisition Cost
--                SET @Net_Purchase_Price =  @Net_Purchase_Price - (ISNULL(@TradeDisc, 0) + isnull(@RebateDisc, 0))
    
--			IF @Use_Other_Disc_GL_Acc = 1    -- 1 = YES
--				BEGIN
--					IF @Other_Disc_GL_Acc = @Purchases_Contol_Acc_ID    --IF Same Account as Purchases
--                        SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)
--				END

--        --> @Use_Other_Disc_GL_Acc = 0    -- 0 = NO
--			ELSE    --> Last_Cost = UnitPrice - (Trade + Rebate + Other) = Net Acquisition Cost
--				SET @Net_Purchase_Price = @Net_Purchase_Price - ISNULL(@OtherDisc, 0)

--------------------------------------------------------------------------
--        --> New Last_Cost
--            SET @New_Last_Cost = ROUND(@Net_Purchase_Price / ISNULL(@Qty, 1), 2)
--------------------------------------------------------------------------
--        --> Updates Last_Cost & Inventory Adjustment for Reval/Deval

--            SET @Note = 'Consignment Received by '

--			EXEC sp_AP_Update_Inventory_Details
--                    @AO_GRV_ID,
--                    @AP_Products_ID,
--					@New_Last_Cost,
--					@New_On_Hand,
--					@Prev_Job_Reserved,
--					@Prev_Sales_Order_Reserved,
--					@Prev_Quote_Reserved,
--					@Note,
--					@UserID ,
--					@CompanyID
--------------------------------------------------------------------------

    	--END
    	
    	
    	
    	
    	IF @AO_Order_Details_ID <> 0 
    		BEGIN
    
    			SELECT @Received_Qty = ISNULL(Received_Qty,0),
    				@Orders_ID = AO_Orders_ID	
    			FROM AO_Order_Details 
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    			
    			SET @Received_Qty =  @Received_Qty + @Qty			 
    		
    			UPDATE AO_Order_Details
    			SET Receipt_Date = GetDate(),
    				Received_Qty = @Received_Qty
    			WHERE AO_Order_Details_ID = @AO_Order_Details_ID
    
            --> CERTIFY ORDER as COMPLETE if items received in full
    			SELECT @Count1 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE AO_Orders_ID = @Orders_ID
    			
    			SELECT @Count2 = Count(AO_Order_Details_ID)
    			FROM AO_Order_Details
    			WHERE Received_Qty  >= (Order_Qty + Back_Order_Qty) AND
                      AO_Orders_ID = @Orders_ID
    			
    			IF @Count2 = @Count1
    				BEGIN
    					UPDATE AO_Orders
    					SET Complete = 1 
    					WHERE AO_Orders_ID = @Orders_ID 
    				END
    		END		
			
		SELECT @chkSOAutoReplenishBO_GRV = Control_Value
		FROM Sys_AW_Options
		WHERE Control_Name = 'chkSOAutoReplenishBO_GRV'
		
		IF @chkSOAutoReplenishBO_GRV = '1'
		BEGIN	
    		--V6.3 RL 2017/04/21 Check if sales orders have back orders	
    		EXEC sp_AO_Update_Sales_Orders @AO_GRV_ID, @AP_Products_ID, @New_On_Hand, @CompanyID	
    	END
				
    END

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

-- Exec sp_AS_SO_Products_Select 1, '1547800', '', ''

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

AS

SET NOCOUNT ON

    DECLARE @SearchType tinyint

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

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		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_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        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.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],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        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 [Gross Profit],
                        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 [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  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 4 Desc, b.On_Hand Desc
	END
	ELSE
	IF @Filter2 <> ''
		BEGIN
			SET @Filter2 = '%' +  @Filter2 + '%'
			SET @Filter1 = '%' +  @Filter1 + '%'

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		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_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        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.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],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        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 [Gross Profit],
                        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 [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1 AND
                  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 4 Desc, b.On_Hand Desc
	END
	ELSE

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

        	SELECT
                		p.Description, 
                		ISNULL(p.Product_Code, '') as [Code],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Price 1],
						CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Stock],
						p.On_Hand AS [Qty On Hand], 
						CONVERT(decimal(9, 3), dbo.fn_AP_SUM_Product_Job_Reserved_Bin (p.AP_Products_ID, b.Lup_AP_Product_Bins_ID)) as [Reserved],
						CONVERT(decimal(9, 3), dbo.fn_AO_Get_Qty_On_Order(p.AP_Products_ID)) as [On Order],
						dbo.GetEffectivePrice(p.Price1_Effective_Date, p.Price1_Price2, p.Price2_Effective_Date, p.Price2_Price2, getdate()) as [Price 2],
						 
                		p.Last_Cost AS [Last Cost], 
                        0 as [Standard Discount],
                		dbo.fn_AP_Get_Sales_Promotion_Price(p.AP_Products_ID, getdate()) as [Promotion],
                		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_Price1, p.Price2_Effective_Date, p.Price2_Price1, getdate()) as [Unit Price],
                		p.Pack_Size AS [Pack Size],
                        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.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],
                        p.AW_User_Companies_ID AS [CompanyID],
                        p.Slu_AW_Active_ID AS [Active],
                        p.Slu_AW_YesNo_Non_Stock_Item AS [NonStockItemID],
						yn2.Description AS [Non Stock Item],
--                        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 [Gross Profit],
                        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 [SellBelowCostID],
						yn1.Description AS [Sell Below Cost],
                        dbo.fn_AP_Get_Consignment_Stock_Qty(p.AP_Products_ID) as [Cons Stock],			
			
						pb.Description AS [Bin],
						b.On_Hand as [Bin On Hand],
						pb.Lup_AP_Product_Bins_ID AS [Bin ID]
        	FROM AP_Products p  
        		LEFT JOIN Sys_AW_Tax_Codes tc
                    ON p.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID
                LEFT OUTER JOIN AP_Products_Bins b
					ON p.AP_Products_ID = b.AP_Products_ID
				LEFT OUTER JOIN Lup_AP_Product_Bins pb
					ON b.Lup_AP_Product_Bins_ID = pb.Lup_AP_Product_Bins_ID
				LEFT OUTER JOIN Slu_AW_YesNo yn1
					ON yn1.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Sell_Below_Cost
				LEFT OUTER JOIN Slu_AW_YesNo yn2
					ON yn2.Slu_AW_YesNo_ID = p.Slu_AW_YesNo_Non_Stock_Item
			WHERE p.AW_User_Companies_ID = @CompanyID AND 
                  p.Slu_AW_Active_ID = 1 AND
                ((p.Description like @Filter1) 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 4 Desc, b.On_Hand Desc
	END
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Sales_Order_Back_Orders]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Sales_Order_Back_Orders]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AS_Select_Sales_Order_Details
--Purpose       :
--Date          :21 JUN 2008
--Authors       :TB
--MODS          :
--2004.3.9      :05/07/08 - Added @OrderType input parameter to separate open
--              :           Back Orders (Type = 0) from Sales Orders (Type = 1)
--2016.6.2	RL	2016-11-01	:Changed sales order search to AS_Transaction tables
--V6.3		RL	:2017/09/19 - Changed column headers
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Select_Sales_Order_Back_Orders]
    (
    	@CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @OrderType tinyint = 0,
        @SortOption tinyint = 0
    )

AS

SET NOCOUNT ON


    IF @OrderType = 0        --Back Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '') AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]						
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], h.Date_Captured
                END
        END

    ELSE                    
    IF @OrderType = 1        --Sales Orders
        BEGIN
            IF @SortOption = 0
                BEGIN
                   SELECT 
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                          d.Back_Order <> 0 AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1
                    ORDER BY [Customer], h.Date_Captured
                END
        END
		ELSE    
        BEGIN
            IF @SortOption = 0
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 1
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY [Product], h.Date_Captured
                END
        
            ELSE
            IF @SortOption = 2
                BEGIN
					SELECT                
                        h.AS_Transactions_ID AS [ID],
                        h.AC_Customers_ID AS [CustomerID],
                        d.AP_Products_ID AS [ProductID],
                        RTRIM(LTRIM(c.Surname)) + ISNULL(', ' + c.Initials, '')AS [Customer],
                        p.[Description] AS [Product],
                        p.Product_Code AS [Code],
						b.Description AS [Bin],
                        h.Transaction_Number As [Trans No],
                        d.Unit_Price AS [Unit Price],
                        (ISNULL(d.Quantity,0) + ISNULL(d.Back_Order,0)) AS [SO Qty],                        
                        ISNULL(d.Back_Order,0) AS [BO Qty],
                        CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID))) as [Qty On Hand],
                		p.On_Hand AS [Stock], 
                        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],
                        h.Date_Captured AS [Captured],
                        u.UserName AS [User],
                        h.[User_ID] AS [UserID],
                        h.AW_User_Companies_ID AS [CompanyID]
                	FROM AS_Transactions h
                		INNER JOIN AS_Transaction_Details d
                			ON h.AS_Transactions_ID = d.AS_Transactions_ID
                        INNER JOIN AP_Products p
                            ON p.AP_Products_ID = d.AP_Products_ID
                        INNER JOIN AC_Customers c
                            ON c.AC_Customers_ID = h.AC_Customers_ID
                        INNER JOIN AW_Users u
                            ON u.AW_Users_ID = h.[User_ID]
						INNER JOIN Lup_AP_Product_Bins b
							ON b.Lup_AP_Product_Bins_ID = d.Lup_AP_Product_Bins_ID
                	WHERE h.AW_User_Companies_ID = @CompanyID AND
                         (DATEDIFF(d, h.Date_Captured, @StartDate) <= 0 AND
                          DATEDIFF(d, h.Date_Captured, @EndDate) >= 0) AND
                          h.Slu_AW_Active_ID = 1 AND
						  h.SYS_AW_Transaction_Types_ID = 16
                    ORDER BY [Customer], h.Date_Captured
                END
        END



SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[vw_AST]') 
            AND type in (N'V'))
DROP VIEW [dbo].[vw_AST]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   : Selects the Transaction for Dynamic reports
--Purpose       : Dynamic SQL statements have a 8,000 character limit
--Functionality : Overcome 8,000 character limit
--Parameters    : 
--Date          : 2017/06/19
--Authors       : RL
--Version       : 1
-------------------------------------------------------------------------------
CREATE     VIEW [dbo].[vw_AST]

AS

    SELECT *
    FROM AS_Transactions
GO


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Sales_Order_No_Stock_CHK]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Sales_Order_No_Stock_CHK]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Sales_Order_No_Stock_CHK
--Purpose       :Check to see if there is stock available on a product before createing sales order
--Date          :2017/09/20
--Authors       :RL
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Sales_Order_No_Stock_CHK]
    (
        @AP_Products_ID	int,
		@Basket_ID	int,
		@Lup_AP_Product_Bins_ID int,
       	@Qty_Available	decimal(18,3) OUTPUT
    )
AS

SET NOCOUNT ON

	DECLARE @Count			int,
			@BO_Qty			decimal(18,3),
			@SO_Qty			decimal(18,3)
   
   
--	SELECT @Qty_Available = CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved(p.AP_Products_ID)))
--  FROM AP_Products p
--	WHERE AP_Products_ID = @AP_Products_ID

	SELECT @Qty_Available = CONVERT(decimal(9, 3),(p.On_Hand - dbo.fn_AP_SUM_Product_Job_Reserved_Bin(p.AP_Products_ID,p.Lup_AP_Product_Bins_ID)))
	FROM AP_Products_Bins p
	WHERE AP_Products_ID = @AP_Products_ID AND
		Lup_AP_Product_Bins_ID = @Lup_AP_Product_Bins_ID

	IF @Qty_Available > 0
	BEGIN
		SELECT  @BO_Qty = Back_Order,
				@SO_Qty = Quantity
		FROM AS_Sales_Order_Details
		WHERE AS_Sales_Order_Details_ID = @Basket_ID

		IF (@Qty_Available - @SO_Qty) >= @BO_Qty
		BEGIN
			UPDATE AS_Sales_Order_Details
				SET Quantity = Quantity + @BO_Qty,
					Back_Order = 0
			WHERE AS_Sales_Order_Details_ID = @Basket_ID
		END
		ELSE
		BEGIN

			UPDATE AS_Sales_Order_Details
				SET Quantity = Quantity + (@Qty_Available - @SO_Qty),
					Back_Order = @BO_Qty - (@Qty_Available - @SO_Qty)
			WHERE AS_Sales_Order_Details_ID = @Basket_ID
		END
	END


	SELECT @Qty_Available As '@Qty_Available'
GO
UPDATE AS_Transactions_Transactions
SET Source_AS_Transactions_ID = 0
Where Source_AS_Transactions_ID IS NULL
Go
UPDATE AS_Transactions_Transactions
SET Destination_AS_Transactions_ID = 0
Where Destination_AS_Transactions_ID IS NULL
GO
EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_Zero]', @objname = N'[dbo].[AS_Transactions_Transactions].[Source_AS_Transactions_ID]'
GO

EXECUTE sp_bindefault @defname = N'[dbo].[df_Numeric_Zero]', @objname = N'[dbo].[AS_Transactions_Transactions].[Destination_AS_Transactions_ID]'
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transactions_Transactions_Source_AS_Transactions_ID'
)
DROP INDEX AS_Transactions_Transactions.IX_AS_Transactions_Transactions_Source_AS_Transactions_ID
GO
CREATE INDEX IX_AS_Transactions_Transactions_Source_AS_Transactions_ID
   ON AS_Transactions_Transactions (Source_AS_Transactions_ID)
	WITH FILLFACTOR = 80
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transactions_Transactions_Destination_AS_Transactions_ID'
)
DROP INDEX AS_Transactions_Transactions.IX_AS_Transactions_Transactions_Destination_AS_Transactions_ID
GO
CREATE INDEX IX_AS_Transactions_Transactions_Destination_AS_Transactions_ID
   ON AS_Transactions_Transactions (Destination_AS_Transactions_ID)
	WITH FILLFACTOR = 80
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AS_Transactions_Transactions_Date_Captured'
)
DROP INDEX AS_Transactions_Transactions.IX_AS_Transactions_Transactions_Date_Captured
GO
CREATE INDEX IX_AS_Transactions_Transactions_Date_Captured
   ON AS_Transactions_Transactions (Date_Captured)
	WITH FILLFACTOR = 80
GO

IF EXISTS 
(
	SELECT name 
	FROM sysindexes 
	WHERE name = 'IX_AC_Statements_AW_Period_Procedures_ID'
)
DROP INDEX AC_Statements.IX_AC_Statements_AW_Period_Procedures_ID
GO
CREATE INDEX IX_AC_Statements_AW_Period_Procedures_ID
   ON AC_Statements (AW_Period_Procedures_ID)
	WITH FILLFACTOR = 80
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Transaction_Document_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Transaction_Document_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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


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

AS

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

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

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

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

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

		EXEC sp_AS_POS_Transaction_Comment_Insert_Update @CommentID OUTPUT, @Comment

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

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

		SELECT @DocumentID = Scope_Identity()

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

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

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

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

		DELETE FROM AO_Order_Candidates
		WHERE Qty <= 0

		DELETE FROM AS_Transaction_Details 
		WHERE AS_Transactions_ID = @VersionNumber

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

		SET @DocumentID = @VersionNumber
	END

RETURN @DocumentID
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Generic_IF_EXISTS]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Generic_IF_EXISTS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Generic_IF_EXISTS
--Purpose       :Generic VALIDATE IF VALUE IN ROW EXISTS
--Date          :2004/12/10
--Authors       :TB
--MODS          :06/03/05 - Added User Catalog validate if User Name EXISTS
--              :08/05/05 - Added Stock Receipts validate if Document_Number EXISTS
--2004.4.2      :08/05/05 - Added POS validate if Customer_Reference EXISTS
--2004.5.2      :09/07/11 - Added Option 5 Supplier Transaction Type = 9 validation
--V6.3	RL		:2017/09/27 - Added Option 6 Customer sales order validation
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Generic_IF_EXISTS]
    (
        @Option tinyint,
        @FieldValue varchar(1000),
        @ActorID int,
        @CompanyID int,
        @Exists bit OUTPUT
    )

AS

SET NOCOUNT ON

    IF @Option = 1
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Product_Code(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 2
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_User_Name(@FieldValue)
        END

    ELSE
    IF @Option = 3
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Supplier_Invoice(@FieldValue, @ActorID, @CompanyID)
        END

    ELSE
    IF @Option = 4
        BEGIN
            SELECT @Exists = dbo.fn_AW_Exists_Customer_Reference(@FieldValue, @ActorID, @CompanyID)
        END

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

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

AS

SET NOCOUNT ON

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


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

    SET @TranNoList = ''


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


	OPEN Transaction_Numbers

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

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

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

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

				SET @TranNoList = @TranNoList + @TranNo
			END

        	FETCH NEXT FROM Transaction_Numbers 
        	INTO
                @TranID

        END

	CLOSE Transaction_Numbers
	DEALLOCATE Transaction_Numbers

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

SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Sales_Order_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Sales_Order_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Sales_Order_Detail
--Purpose       :Selects Customer Sales Orders Detail Shaped
--Date          :2008/06/17
--Authors       :TB
--Mods          :
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON


    SELECT d.AS_Transaction_Details_ID AS [ID],
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product],
           p.Product_Code AS [Code],
		   b.Description AS [Bin],
           d.Unit_Price AS [Unit Price],
           d.Quantity AS [Qty],
           d.Back_Order AS [B/O],
           d.Discount_Amount AS [Discount],
           CONVERT(money, (d.Extended_Amount - d.Tax_Amount)) AS [Amount],
           d.Tax_Amount AS [Tax],
           d.Extended_Amount AS [Total],
           d.Original_Price AS [Orig Price],
           CASE WHEN (d.Extended_Amount - d.Tax_Amount) <> 0
                THEN CONVERT(decimal(9, 3), ROUND((d.Tax_Amount / (d.Extended_Amount - d.Tax_Amount)) * 100, 2))
                ELSE 0.00
           END AS [Tax Rate],
           d.Unit_Cost AS [Unit Cost]		   
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Lup_AP_Product_Bins b
			ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID
    ORDER BY [ID]
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Shape_Uninvoiced_Sales_Orders_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Shape_Transaction_Detail
--Purpose       :Selects Uninvoiced Sales Orders Detail Shaped
--Date          :2008/07/24
--Authors       :TB
--MODS          :
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    SELECT d.AS_Transaction_Details_ID AS [ID], 
           d.AS_Transactions_ID AS [TransactionID],
           d.AP_Products_ID AS [ProductID],
           p.[Description] AS [Product], 
           p.Product_Code AS [Code],
		   b.Description AS [Bin], 
           d.Quantity AS [Qty],
           d.Unit_Cost AS [Cost], 
           d.Unit_Price AS [Price], 
           d.Original_Price AS [Orig Price], 
           d.Discount_Amount AS [Discount], 
           d.Tax_Amount AS [Tax], 
           d.Extended_Amount AS [Total] 
    FROM AS_Transaction_Details d
        LEFT JOIN AP_Products p
            ON d.AP_Products_ID = p.AP_Products_ID
		LEFT JOIN Lup_AP_Product_Bins b
			ON d.Lup_AP_Product_Bins_ID = b.Lup_AP_Product_Bins_ID
    WHERE d.AS_Transactions_ID = @TransactionID
GO
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

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Xref]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Xref]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AS_Transactions_Xref
--Purpose       :INSERTS AS_Transactions_Xref row and
--              :deactivates recalled AS_Transactions used as source in POS
--              :
--Date			:2002/12/26
--Authors		:TB
--MODS          :22/05/04 - Added decrement the RESERVED values in AP_Products
--2004.4.8      :26/04/10 - Commented Decrement the RESERVED values - NO LONGER USED
--V6.3	RL	2017-10-10	:Added Back Order Functionality
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Transactions_Xref]
	(
		@SourceTranID int,
		@DestinTranID int,
        @UserID int,
        @CompanyID int
	)

AS

SET NOCOUNT ON

    DECLARE @XrefID int
--             @ProductID int,
--             @Qty decimal(9, 3),
--             @Reserved decimal(9, 3),
--             @TranTypeID tinyint
    
    BEGIN

        IF NOT EXISTS
            (
                SELECT AS_Transactions_Xref_ID
                FROM AS_Transactions_Xref
                WHERE AS_Transactions_ID = @DestinTranID
    
            )
            BEGIN
                INSERT AS_Transactions_Xref
                    (
                        AS_Transactions_ID,
                        [User_ID],
                        AW_User_Companies_ID
                    )
                VALUES
                    (
                        @DestinTranID,
                        @UserID,
                        @CompanyID
                    )

                SET @XrefID = (SELECT scope_identity())

            END
        ELSE
            BEGIN
                SELECT @XrefID = AS_Transactions_Xref_ID
                FROM AS_Transactions_Xref
                WHERE AS_Transactions_ID = @DestinTranID
            END

--------------------------------------------------------
-- INSERT the Transactions Xref
--------------------------------------------------------
        INSERT AS_Transactions_Xref_Sources
            (
                AS_Transactions_Xref_ID,
                AS_Transactions_ID,
                [User_ID],
                AW_User_Companies_ID
            )
        VALUES
            (
                @XrefID,
                @SourceTranID,
                @UserID,
                @CompanyID
            )

--------------------------------------------------------
-- DE-ACTIVATE the Source Transaction
--------------------------------------------------------
        UPDATE AS_Transactions
        SET Slu_AW_Active_ID = 0
        WHERE AS_Transactions_ID = @SourceTranID

--------------------------------------------------------
-- Remove back order items placed in the purchase order shopping list
--------------------------------------------------------
		IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions
			WHERE AS_Transactions_ID = @SourceTranID AND
				Sys_AW_Transaction_Types_ID = 16
		)
		BEGIN
			UPDATE AO_Order_Candidates
			SET Qty = Qty - Back_Order
			FROM AO_Order_Candidates o
				INNER JOIN AS_Transaction_Details d
					On o.AP_Products_ID = d.AP_Products_ID
			WHERE d.AS_Transactions_ID = @SourceTranID AND
				Back_Order <> 0

			DELETE FROM AO_Order_Candidates
			WHERE Qty <= 0
		END



-- COMMENTED 2004.4.8 - NO LONGER USED
-- --------------------------------------------------------
-- -- Decrement the RESERVED values
-- --------------------------------------------------------
-- 
--         SELECT @TranTypeID = Sys_AW_Transaction_Types_ID
--         FROM AS_Transactions
--         WHERE AS_Transactions_ID = @SourceTranID
-- 
-- 
--     --> Define a CURSOR to update the RESERVED in AP_Products
--     	DECLARE Tran_Cursor CURSOR FOR
--             (
--                 SELECT AP_Products_ID,
--                        ISNULL(Quantity, 0)
--                 FROM AS_Transaction_Details
--                 WHERE AS_Transactions_ID = @SourceTranID
--             )
--     
--     	OPEN Tran_Cursor
--     
--         	FETCH NEXT FROM Tran_Cursor 
--         	INTO
--                 @ProductID,
--                 @Qty
-- 
--         	
--         	WHILE @@FETCH_STATUS = 0
--         	BEGIN
-- 
--                 IF @TranTypeID = 1        --Quote
--                     BEGIN
--                         SELECT @Reserved = Quote_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Quote_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Quote_Reserved = Quote_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
--                 ELSE
--                 IF @TranTypeID = 2        --Jobcard
--                     BEGIN
--                         SELECT @Reserved = Job_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Job_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Job_Reserved = Job_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
-- 
-- 
--                 ELSE
--                 IF @TranTypeID = 16       --Sales Order
--                     BEGIN
--                         SELECT @Reserved = Sales_Order_Reserved
--                         FROM AP_Products
--                         WHERE AP_Products_ID = @ProductID
-- 
--                         IF @Reserved - @Qty < 0
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Sales_Order_Reserved = 0
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                         ELSE
--                             BEGIN
--                                 UPDATE AP_Products
--                                 SET Sales_Order_Reserved = Sales_Order_Reserved - @Qty
--                                 WHERE AP_Products_ID = @ProductID
--                             END
--                     END
-- 
-- 
-- 
--             	FETCH NEXT FROM Tran_Cursor 
--             	INTO
--                     @ProductID,
--                     @Qty
--         
--             END
--     	
--     	CLOSE Tran_Cursor
--     
--     	DEALLOCATE Tran_Cursor


    END


SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_Product_Job_SO_Reserved_NO_BO]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_Product_Job_SO_Reserved_NO_BO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_SO_Reserved_NO_BO
--Purpose       :Fetch the JOB RESERVED and Sales Orders Qty Excluding Back Orders
--Functionality :Returns the value from a SCALAR function
--Date          :2017/10/10
--Authors       :RL
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AP_Get_Product_Job_SO_Reserved_NO_BO]
    (
        @ProductID int,
        @Reserved float OUTPUT
    )

AS

SET NOCOUNT ON


    SELECT @Reserved = dbo.fn_AP_SUM_Product_Job_SO_Reserved_NO_BO(@ProductID)



SET NOCOUNT OFF
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO
--Purpose       :Fetch the JOB RESERVED Qty for ONE Product and Bin on ALL OPEN Jobcards
--Date          :2017/10/10
--Authors       :RL
-------------------------------------------------------------------------------

CREATE PROCEDURE [sp_AP_Get_Product_Job_SO_Reserved_Bin_NO_BO]
    (
        @ProductID int,
        @ProductBinID int,
        @Reserved float OUTPUT
    )
AS

SET NOCOUNT ON

        SELECT @Reserved = 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
			  d.Lup_AP_Product_Bins_ID = @ProductBinID AND
              h.Slu_AW_Active_ID = 1 AND
             (h.Sys_AW_Transaction_Types_ID = 2 OR
              h.Sys_AW_Transaction_Types_ID = 16)
 
SET NOCOUNT OFF
GO
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AB_GL_Transactions_DEL' 
    AND type = 'TR'
)
DROP TRIGGER trg_AB_GL_Transactions_DEL
GO
CREATE TRIGGER [dbo].[trg_AB_GL_Transactions_DEL] ON [dbo].[AB_GL_Transactions]
FOR DELETE 
AS
BEGIN
	INSERT INTO AB_GL_Transactions_Audit
	(
		Record_Action, 
		AB_GL_Transactions_ID, 
		Field, 
		Prev_Value, 
		New_Value,
		Date_Captured, 
		[User_ID]
	)
	SELECT
		'Delete', 
		AB_GL_Transactions_ID, 
		'', 
		IsNull([Description],''),
		IsNull(AB_Source_Ref,''),
		GetDate(), 
		1
    FROM Deleted     
END
GO
IF EXISTS 
(
	SELECT * 
	FROM sysobjects
    WHERE name = 'trg_AB_GL_Transactions_UPD' 
    AND type = 'TR'
)
DROP TRIGGER [trg_AB_GL_Transactions_UPD]
GO
CREATE TRIGGER [dbo].[trg_AB_GL_Transactions_UPD] ON [dbo].[AB_GL_Transactions]
AFTER UPDATE 
AS
BEGIN

	DECLARE @AB_GL_Transactions_ID	Int,	
	
	--Deleted Data
	@d_Description						Varchar(50), 
	@d_Sys_AB_Transaction_Types_ID		Int,
	@d_AB_Accounts_ID					Int, 
	@d_AB_Transaction_Date				Datetime, 
	@d_AB_Source_Ref					Varchar(20),  
	@d_Slu_AW_Months_ID					Int, 
	@d_Slu_AW_Years_ID					Int, 
	@d_AB_Transaction_Ref				Int,
	@d_AB_Transaction_Amount			Money,
	@d_Slu_AW_Active_ID					Int, 
	
	--Inserted Data
	@i_Description						Varchar(50), 
	@i_Sys_AB_Transaction_Types_ID		Int,
	@i_AB_Accounts_ID					Int, 
	@i_AB_Transaction_Date				Datetime, 
	@i_AB_Source_Ref					Varchar(20),  
	@i_Slu_AW_Months_ID					Int, 
	@i_Slu_AW_Years_ID					Int, 
	@i_AB_Transaction_Ref				Int,
	@i_AB_Transaction_Amount			Money,
	@i_Slu_AW_Active_ID					Int,
	@i_User_ID							Int
	
	SELECT
		@AB_GL_Transactions_ID = AB_GL_Transactions_ID ,
		@d_Description = IsNull(Description,''),
		@d_Sys_AB_Transaction_Types_ID = IsNull(Sys_AB_Transaction_Types_ID,0),
		@d_AB_Accounts_ID = IsNull(AB_Accounts_ID,0),
		@d_AB_Transaction_Date = IsNull(AB_Transaction_Date,'1999-01-01'),
		@d_AB_Source_Ref = IsNull(AB_Source_Ref,''),
		@d_Slu_AW_Months_ID = IsNull(Slu_AW_Months_ID,0),
		@d_Slu_AW_Years_ID = IsNull(Slu_AW_Years_ID,0),
		@d_AB_Transaction_Ref = IsNull(AB_Transaction_Ref,0),
		@d_AB_Transaction_Amount = IsNull(AB_Transaction_Amount,0),
		@d_Slu_AW_Active_ID = IsNull(Slu_AW_Active_ID,0)
	FROM DELETED		
	
	SELECT 
		@i_Description = IsNull(Description,''),
		@i_Sys_AB_Transaction_Types_ID = IsNull(Sys_AB_Transaction_Types_ID,0),
		@i_AB_Accounts_ID = IsNull(AB_Accounts_ID,0),
		@i_AB_Transaction_Date = IsNull(AB_Transaction_Date,'1999-01-01'),
		@i_AB_Source_Ref = IsNull(AB_Source_Ref,''),

		@i_Slu_AW_Months_ID = IsNull(Slu_AW_Months_ID,0),
		@i_Slu_AW_Years_ID = IsNull(Slu_AW_Years_ID,0),
		@i_AB_Transaction_Ref = IsNull(AB_Transaction_Ref,0),
		@i_AB_Transaction_Amount = IsNull(AB_Transaction_Amount,0),
		@i_Slu_AW_Active_ID = IsNull(Slu_AW_Active_ID,0),
		@i_User_ID = [User_ID]
	FROM INSERTED		
	
	IF @d_Description <> @i_Description
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'Description', @d_Description, @i_Description, GetDate(), @i_User_ID)
	END	
	IF @d_Sys_AB_Transaction_Types_ID <> @i_Sys_AB_Transaction_Types_ID
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'Sys_AB_Transaction_Types_ID', CONVERT(VARCHAR(50),ISNULL(@d_Sys_AB_Transaction_Types_ID,0)), CONVERT(VARCHAR(50),ISNULL(@i_Sys_AB_Transaction_Types_ID,0)), GetDate(), @i_User_ID)
	END	
	IF @d_AB_Accounts_ID <> @i_AB_Accounts_ID
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'AB_Accounts_ID', CONVERT(VARCHAR(50),ISNULL(@d_AB_Accounts_ID,0)), CONVERT(VARCHAR(50),ISNULL(@i_AB_Accounts_ID,0)), GetDate(), @i_User_ID)
	END	
	IF @d_AB_Transaction_Date <> @i_AB_Transaction_Date
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'AB_Transaction_Date', CONVERT(VARCHAR(50),ISNULL(@d_AB_Transaction_Date,0),121), CONVERT(VARCHAR(50),ISNULL(@i_AB_Transaction_Date,0),121), GetDate(), @i_User_ID)
	END	
	IF @d_AB_Source_Ref <> @i_AB_Source_Ref
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'AB_Source_Ref', @d_AB_Source_Ref, @i_AB_Source_Ref, GetDate(), @i_User_ID)
	END	
	IF @d_Slu_AW_Months_ID <> @i_Slu_AW_Months_ID
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'Slu_AW_Months_ID', CONVERT(VARCHAR(50),ISNULL(@d_Slu_AW_Months_ID,0)), CONVERT(VARCHAR(50),ISNULL(@i_Slu_AW_Months_ID,0)), GetDate(), @i_User_ID)
	END	

	IF @d_Slu_AW_Years_ID <> @i_Slu_AW_Years_ID
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'Slu_AW_Years_ID', CONVERT(VARCHAR(50),ISNULL(@d_Slu_AW_Years_ID,0)), CONVERT(VARCHAR(50),ISNULL(@i_Slu_AW_Years_ID,0)), GetDate(), @i_User_ID)
	END	

	IF @d_AB_Transaction_Ref <> @i_AB_Transaction_Ref
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'AB_Transaction_Ref', CONVERT(VARCHAR(50),ISNULL(@d_AB_Transaction_Ref,0)), CONVERT(VARCHAR(50),ISNULL(@i_AB_Transaction_Ref,0)), GetDate(), @i_User_ID)
	END	
	IF @d_AB_Transaction_Amount <> @i_AB_Transaction_Amount
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'AB_Transaction_Amount', CONVERT(VARCHAR(50),ISNULL(@d_AB_Transaction_Amount,0)), CONVERT(VARCHAR(50),ISNULL(@i_AB_Transaction_Amount,0)), GetDate(), @i_User_ID)
	END	
	IF @d_Slu_AW_Active_ID <> @i_Slu_AW_Active_ID
	BEGIN
		INSERT INTO AB_GL_Transactions_Audit(Record_Action, AB_GL_Transactions_ID, Field, Prev_Value, New_Value, Date_Captured, [User_ID])
		VALUES('Update', @AB_GL_Transactions_ID, 'Slu_AW_Active_ID', CONVERT(VARCHAR(50),ISNULL(@d_Slu_AW_Active_ID,0)), CONVERT(VARCHAR(50),ISNULL(@i_Slu_AW_Active_ID,0)), GetDate(), @i_User_ID)
	END	
End
GO
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Check_Till_Supervisor_Status]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Check_Till_Supervisor_Status]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Check_Till_Supervisor_Status
--Purpose       :Select if User = Supervisor
--Functionality :User MUST BE IsTillPayout to authorise
--Date          :2017/10/19
--Authors       :RL
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

    SET @TillSupervisor = 0

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

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

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

AS

SET NOCOUNT ON

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

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







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

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

AS

SET NOCOUNT ON

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


    SET @WhichAddress = 0


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

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

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


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


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

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

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

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

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

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

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

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


SET NOCOUNT OFF
GO
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------

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

GO
