------------------------------------------------------------------------------
-- ADVANTAGE 2004.5.9.3950
-- NEW OPTIONS, LOOKUPS and APPLICATIONS
-- 2013-08-12
------------------------------------------------------------------------------

--1 sp_AS_Delete_Day_End
/****** Object:  StoredProcedure [dbo].[sp_AS_Delete_Day_End]    Script Date: 09/24/2012 05:28:57 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Delete_Day_End]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Delete_Day_End]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Delete_Day_End
--Purpose       :DELETE Day-End procedure
--Date          :2011/08/09
--Authors       :TB
--MODS          :
--2004.5.5      :31/10/11 - Fixed Journal_Narration from 'Day End - Sales' to be
--              :           'Day End - Debtors Sales' as it is written in AB_Journals !!!
--              :31/10/11 - Replaced the REVERSAL of the Journal and GL Transactions code
--              :           with DELETE of the Journal and GL Transactions and UPDATING
--              :           the GL Account Balance with the REVERSAL AMOUNT
--              :           This is preferable to reversing a potentially OUT-OF-BALANCE
--              :           GL Transaction and Journal that puts the GL back in balance
--              :03/11/11 - Modified to delete AS_Day-Ends and reset Day-End flag even if
--              :           Day-End journal not found - to enable delete EMPTY Day-Ends
--2004.5.9 RL   :2013-05-06 Added extra Journal_Narrations to find day ends
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Delete_Day_End]
	(
		@DayEndID int,
        @DayEndDate datetime,
		@GLTranRef int,
        @GLTranDate datetime,
        @UserID int,
        @CompanyID int
	)
AS

SET NOCOUNT ON

    DECLARE @JournalID int,
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
            @GLAccountID int,
            @Amount money,
            @Notes varchar(50),
    		@Month tinyint,
    		@Year int,
            @InsertGLTran bit,
            @RetCode int

    SET @RetCode = 0
    SET @NextGLTranID = 0
    SET @JNLHeaderID = 0
    SET @InsertGLTran = 0            --0 = Do Not insert a GL Transaction in JNL Details
    SET @JournalID = 0


    SELECT TOP 1 @Month = Slu_AW_Months_ID,
                 @Year = Slu_AW_Years_ID
    FROM AB_GL_Transactions
    WHERE AB_Transaction_Ref = @GLTranRef AND
          Sys_AB_Transaction_Types_ID = 22 AND
          Description = 'Day End - Sales'


    --> STRIP milliseconds using CONVERT(CHAR(19)
    SELECT @JournalID = AB_Journals_ID
    FROM AB_Journals
    WHERE CONVERT(CHAR(19), Journal_Date) = CONVERT(CHAR(19), @GLTranDate) AND
          Journal_Reference = CONVERT(varchar(30), @GLTranRef) AND
	--> Ver 5.9, RL, Added extra Journal_Narrations to find day ends
          Journal_Narration IN ('Day End - Debtors Sales',
                                'Day End - Sales',
                                'Day End - Receipts',
                                'Day End - POS Receipts',
                                'Day End - Total Receipts',
                                'Day End - Settlement Discount',
                                'Day End - Interest Journals',
                                'Day End - OTHER Receipts')


    IF @JournalID > 0
        BEGIN
        	DECLARE DELETE_DAYEND CURSOR FOR
                (
                    SELECT AB_Accounts_ID,
                           Amount,
                           Notes
                    FROM AB_Journal_Details
                    WHERE AB_Journals_ID = @JournalID
                )

        	OPEN DELETE_DAYEND

            	FETCH NEXT FROM DELETE_DAYEND 
            	INTO
                    @GLAccountID,
                    @Amount,
                    @Notes

            	WHILE @@FETCH_STATUS = 0
            	BEGIN
                    -- NEW CODE - 2004.5.5
                    SET @Amount = @Amount * -1


                    UPDATE AB_Accounts
                    SET AB_Account_Balance = AB_Account_Balance + @Amount
                    WHERE AW_User_Companies_ID = @CompanyID AND
                          AB_Accounts_ID = @GLAccountID 


                    DELETE
                    FROM AB_GL_Transactions
                    WHERE Sys_AB_Transaction_Types_ID = 22 AND
                          AB_Accounts_ID = @GLAccountID AND
                          AB_Transaction_Date = @GLTranDate AND
                          AB_Transaction_Ref = @GLTranRef


                	FETCH NEXT FROM DELETE_DAYEND 
                	INTO
                        @GLAccountID,
                        @Amount,
                        @Notes
                END

        	CLOSE DELETE_DAYEND
        
        	DEALLOCATE DELETE_DAYEND


            --> DELETE the Journal Details - NEW 2004.5.5
            DELETE
            FROM AB_Journal_Details
            WHERE AB_Journals_ID = @JournalID


            --> DELETE the Journal Header - NEW 2004.5.5
            DELETE
            FROM AB_Journals
            WHERE AB_Journals_ID = @JournalID
        END


        --> RESET the Day-End flag
        UPDATE AS_Transactions
        SET Day_End = NULL
        WHERE Day_End = @DayEndDate

        --> RESET the Day-End flag
        UPDATE AS_Till_Payouts
        SET Day_End = NULL
        WHERE Day_End = @DayEndDate

        --> DELETE the Day-End
        DELETE
        FROM AS_Day_Ends
        WHERE AS_Day_Ends_ID = @DayEndID


        SET @RetCode = 1


RETURN @RetCode
SET NOCOUNT OFF

GO

--2 sp_AC_Check_Cellphone
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Check_Cellphone]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].sp_AC_Check_Cellphone
GO

/****** Object:  StoredProcedure [dbo].[sp_AC_Check_Cellphone]    Script Date: 05/06/2013 16:07:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AC_Check_Cellphone
--Purpose       :Format Cellphone Numbers
--Date          :2012-10-01
--Authors       :RGL
--MODS          :
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Check_Cellphone]
    (
        @intCountryID           int,
        @intCustomerID          int,        
        @strCellphone	        varchar(20),
        @strCellphone_Formated	varchar(20)OUTPUT
    )
AS

SET NOCOUNT ON

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

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

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

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

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

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

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

GO

--3 sp_AS_Day_End
/****** Object:  StoredProcedure [dbo].[sp_AS_Day_End]    Script Date: 09/24/2012 05:28:57 ******/
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 QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS 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
-------------------------------------------------------------------------------
---- 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 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

	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
                                    22,
                                    @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,
                            22,
                            @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,
                            22,
                            @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,
                            22,
                            @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 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,
                    @DayEndDate,
                    @Month,
                    @Year,
                    @NextGLTranID,
                    @DayEndDate,
                    @UserID,
                    @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 = @CutOffDate

			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

--4 sp_AO_Insert_AO_Transactions
/****** Object:  StoredProcedure [dbo].[sp_AO_Insert_AO_Transactions]    Script Date: 06/11/2013 15:32:04 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Insert_AO_Transactions]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Insert_AO_Transactions]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

------------------------------------------------------------------------------
--Description   :sp_AO_Insert_AO_Transactions
--Purpose       :Supplier Invoice/Credit Note INSERT from GL Control Accounts
--              :    (not Product-based Purchases GL Account)
--Functionality :1. Inserts a Supplier Invoice/Credit Note into AO_Transactions for
--              :    1.1 Stock Receipts (GRV)
--              :    1.2 Supplier Invoices
--              :2. GL Transaction insert for Purchases, Creditors, VAT, Discounts
--              :3. SPLIT GRV to GL Cost-of-Sales Accounts by Product Type
--              :    using chkUseProductPurchasesGL parameter
--Date          :2002/04/03
--Authors       :TB
--Mods          :19/06/02 - Fixed Sys_AB_Transaction_Types_ID insert into GL Tran
--              :            by setting new var @ABTranTypeID
--              :24/06/02 - Double Entry REQUIRES ALL @Trade_Creditors_GL_Acc_ID
--              :             (Invoice and Credit Note) amounts to be REVERSED
--              :24/07/02 - Added parameter @GLAccountID to enable selecting
--              :           any GL Account in Supplier Invoices
--              :14/08/02 - Removed convert Amounts to NEG for Credit Notes.
--              :           ALL amounts changed to NEG in UI.txtInv_GotFocus
--              :16/08/02 - Insert @GLAccountID into AO_Transactions NEW column
--              :               AB_Accounts_ID
--              :28/10/02 - Added insert MonthID and YearsID to AO_Transactions
--              :29/10/02 - Added DEFAULT to Purchases Control if @GLAccountID = 0
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :08/12/03 - Added NEW @Comment field from Supplier Invoices/Refunds
--              :11/12/03 - Added RETURN @New_Suppliers_Invoice_ID to
--              :           accommodate NEW Supplier Multi-Split Transactions 
--              :13/12/03 - Fixed Supplier Invoicing bug caused by length of
--              :           @Invoice_No below defined as varchar(10) s/b (20)
--              :25/07/04 - Added text in 'Comment' field in Stock Receipts UI
--              :           SaveGReceivedV and SaveGReturnedV to distinguish
--              :           between tran source i.e. Supplier Invoice & GRV Invoice
--              :           and replaced @SupplierName with @GLDescription
--2004.2.5      :14/01/06 - Replaced input parameter DECLARE of currency types
--              :           of DECIMAL(14,6) declarations with type MONEY
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--              :04/10/06 - Added GRV Item Purchases SPLIT by PRODUCT TYPE and
--              :           inserts GL Transactions to GL C.O.S. ACCOUNTS
--2004.3.5      :23/06/07 - Initalise @SupplierRef and @Comment to NULL STRING
--              :           and removed their NULL input parameter initialising 
--              :           If NULL then combined GL Description is NULL
--2004.3.8      :27/04/08 - Added INSERT into new AO_Transactions_Log for transactions
--              :           posted to Accounting Period of LAST SUPPLIERS MONTH-END
--              :           or earlier
--              :30/04/08 - Added Update Suppliers Account Balance !!!!
--              :30/04/08 - Extended TRANSACTION Save_Supplier_Invoice to include
--              :           all the GL inserts
--2004.4.3      :08/02/09 - Modified to Split GRV Stock Receipts from post to GL C.O.S.
--              :           accounts to post to GL INVENTORY accounts by Product Type - RM
--2004.4.8      :06/11/09 - Modified to ONLY insert VAT Control GL entry if VAT <> 0
--2004.5.0      :18/02/11 - Added NORMAL Continuous Inventory posting to INVENTORY GL Account !!!!!!
--              :           Was previously determined by 301 Purchases Control Account setting !!!!!
--2004.5.7 RGL  :2012-10-23 - Posted GRV for levy items to GL as setup on the Ap_Products table
--2004.5.9 RGL  :2013-06-19 - Fixed bug. Rebate and Other discounts not written to adjustment GLs as 
--							  setup in supplier catelog. Adjustments value also added to inventory GL
------------------------------------------------------------------------------
--Supplier Invoice = 8, @ABTranTypeID = 5
--Supplier Refund = 9, @ABTranTypeID = 6
------------------------------------------------------------------------------
CREATE Procedure [dbo].[sp_AO_Insert_AO_Transactions]
    (
    	@Suppliers_ID int,
    	@SupplierRef varchar(20),
    	@Transaction_Type tinyint,		
    	@Invoice_No varchar(20),
    	@Invoice_Date datetime,
    	@AO_GRV_ID int = null,
    	@TradeDisc money = 0,
    	@RebateDisc money = 0,
    	@OtherDisc money = 0,
    	@NetAmount money = 0,
    	@TaxTotal Money = 0,
    	@TotalAmount Money = 0,
    	@MonthsID int, 
    	@YearsID int,
    	@UserID int,
    	@CompanyID int,
        @GLAccountID int = 0,
        @Comment varchar(20)
    )
AS

SET NOCOUNT ON

    DECLARE @TempRebateDisc money,
            @TempOtherDisc money,
            @Tax_Rate Decimal(5,2),
            @New_Suppliers_Invoice_ID int,
            @Use_Rebate_Disc bit,
            @Use_Other_Disc bit,
            @Rebate_Disc_GL_Acc_ID int,
            @Other_Disc_GL_Acc_ID int,
            @Trade_Creditors_GL_Acc_ID int,	
            @Purchases_GL_Acc_ID int,
            @VAT_GL_Acc_ID int,
            @SupplierName varchar(30),
            
            @Rebate_VAT_Amount money,
            @Other_VAT_Amount money,
            @Trade_Creditors_VAT_Amount money,
            @VAT_Contol_Amount money,
            @Trade_Creditors_Amount money,
            @Net_Purchase_Price money,
            @Rebate_Disc_Amount money,
            @Other_Discount_Amount money,
            
            @ABTranTypeID tinyint,
            @GLDescription varchar(70),
            @LENSupplier int,
            @LENComment int,
            @NormalCOSparameter varchar(10),
            @SplitCOSparameter varchar(10),
            @GLPurchasesID int,
            @SplitGLAccount  varchar(50),
            @InventoryGLDescription varchar(50),
            @GRVAmount money,
            @GLInventoryID int,
            @NormalCOSTypes int,
            @SplitCOSTypes int,
            
            --> Supplier Transaction Log fields
            @Current_Month_ID tinyint,
            @Current_Year_ID int,
            @LastME_Month_ID tinyint,
            @LastME_Year_ID int,
            @LastMEPeriod varchar(6),
            @TranGLPeriod varchar(6)


    SET @SupplierRef = ISNULL(@SupplierRef, '')
    SET @Comment = ISNULL(@Comment, '')


    ---------------------------------------------------------------
    --> GET LAST Suppliers Month-End and Current Accounting Period
    ---------------------------------------------------------------
    SELECT TOP 1 @LastME_Month_ID = [Month],
                 @LastME_Year_ID = [Year]
    FROM  AW_Period_Procedures
    WHERE AW_User_Companies_ID = @CompanyID AND
          Sys_AW_Period_Procedure_Types_ID = 6
    ORDER BY dbo.fn_AB_Get_Ending_GL_Period([Month], [Year]) DESC

    SET @LastMEPeriod = dbo.fn_AB_Get_Ending_GL_Period(@LastME_Month_ID, @LastME_Year_ID)
    SET @TranGLPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthsID, @YearsID)


    SELECT @Current_Month_ID = Slu_AW_Months_ID,
           @Current_Year_ID = Slu_AW_Years_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID
    ---------------------------------------------------------------


    BEGIN TRAN Save_Supplier_Invoice
    	BEGIN	
            -------------------------------------------------------
        --> Get the STANDARD VAT rate
            -------------------------------------------------------
            SELECT @Tax_Rate = Tax_Rate
            FROM Sys_AW_Tax_Codes
            WHERE Tax_Code = 'S'
    
            IF @Tax_Rate IS NULL
                SET @Tax_Rate = 0
            ELSE
                SET @Tax_Rate = @Tax_Rate / 100

            -------------------------------------------------------
        --> Get NORMAL Continuous Inventory to GL Inventory accounts parameter - NEW 2004.5.0
            -------------------------------------------------------
            SET @NormalCOSparameter = '0'

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

            -------------------------------------------------------
        --> ONLY set @NormalCOSTypes if @NormalCOSparameter = '1' and this is a GRV - NEW 2004.5.0
            -------------------------------------------------------
            SET @NormalCOSTypes = 0

            IF @NormalCOSparameter = '1' AND @AO_GRV_ID > 0
                BEGIN
                    SET @NormalCOSTypes = 1
                END


            -------------------------------------------------------
        --> Get Split GRV Stock Receipts to GL Inventory accounts parameter
            -------------------------------------------------------
            SET @SplitCOSparameter = '0'

            SELECT @SplitCOSparameter = 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 @SplitCOSTypes if @SplitCOSparameter = '1' and this is a GRV
            -------------------------------------------------------
            SET @SplitCOSTypes = 0

            IF @SplitCOSparameter = '1' AND @AO_GRV_ID > 0
                BEGIN
                    SET @SplitCOSTypes = 1
                END


            -------------------------------------------------------
        --> Get ALL the GL Control Accounts
            -------------------------------------------------------    
            SELECT @Trade_Creditors_GL_Acc_ID = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 201                        -- Trade Creditors Control


            -------------------------------------------------------
        --> Get NORMAL Continuous Inventory GL INVENTORY Control Account - NEW 2004.5.0
            ------------------------------------------------------- 
            IF @NormalCOSTypes = 1                            -- NORMAL Continuous Inventory
                BEGIN
                    SELECT @GLAccountID = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 601                -- INVENTORY
                END
            ------------------------------------------------------- 


            IF @GLAccountID = 0 OR @GLAccountID IS NULL       -- No GL Account was supplied
                BEGIN
                    SELECT @Purchases_GL_Acc_ID = AB_Accounts_ID
                    FROM AB_Control_Accounts
                    WHERE Control_Number = 301                -- Purchases
                END
            ELSE
                BEGIN
                    SET @Purchases_GL_Acc_ID = @GLAccountID
                END


            SELECT @VAT_GL_Acc_ID = AB_Accounts_ID
            FROM AB_Control_Accounts
            WHERE Control_Number = 401    -- VAT Control
            -------------------------------------------------------


            -------------------------------------------------------
            -- If @SplitCOSparameter posting is used the GL_Accounts_ID
            -- will still insert a single AO_Transactions for the GRV
            -- and reference @Purchases_GL_Acc_ID as before - RM
            -------------------------------------------------------
			INSERT INTO AO_Transactions
				(
                    AO_Suppliers_ID,
                    AB_Accounts_ID,
                    Supplier_Reference,
                    Sys_AW_Transaction_Types_ID,
                    Document_Number,
                    Document_Date,
                    Slu_AW_Months_ID,
                    Slu_AW_Years_ID,
                    AO_GRV_ID,
                    Comment,
                    Trade_Discount_Total,
                    Rebate_Discount_Total,
                    Other_Discount_Total,
                    Net_Amount,
                    Total_Tax_Amount,
                    Total_Amount,
                    Payment_Amount,
                    [User_ID],
                    AW_User_Companies_ID
                )
			VALUES
                (
                    @Suppliers_ID,
                    @Purchases_GL_Acc_ID,
                    @SupplierRef,
                    @Transaction_Type,
                    @Invoice_No,
                    @Invoice_Date,
                    @MonthsID,
                    @YearsID,
                    @AO_GRV_ID,
                    @Comment,
                    @TradeDisc,
                    @RebateDisc,
                    @OtherDisc,
                    @NetAmount,
                    @TaxTotal,
                    @TotalAmount,
                    0,
                    @UserID,
                    @CompanyID
                )
    	
            SELECT @New_Suppliers_Invoice_ID = SCOPE_IDENTITY()


        --> NEW 2004.3.8 - UPDATE Supplier Account Balance
        	UPDATE AO_Suppliers
            SET Account_Balance = Account_Balance + @TotalAmount
            WHERE AO_Suppliers_ID = @Suppliers_ID
    
    
            ---------------------------------------------------------------
            --> INSERT Supplier Transaction Log
            ---------------------------------------------------------------
            IF @TranGLPeriod <= @LastMEPeriod
                BEGIN
                    INSERT AO_Transactions_Log
                        (
                            AO_Suppliers_ID,
                            AO_Transactions_ID,
                            AO_GRV_ID,
                            Posted_Month_ID,
                            Posted_Year_ID,
                            Current_Month_ID,
                            Current_Year_ID,
                            LastME_Month_ID,
                            LastME_Year_ID,
                            [User_ID],
                            AW_User_Companies_ID
                        )
        
                    VALUES
                        (
                            @Suppliers_ID,
                            @New_Suppliers_Invoice_ID,
                            @AO_GRV_ID,
                            @MonthsID,
                            @YearsID,
                            @Current_Month_ID,
                            @Current_Year_ID,
                            @LastME_Month_ID,
                            @LastME_Year_ID,
                            @UserID,
                            @CompanyID
                        )
                END
            ---------------------------------------------------------------
    
    
    		SET @Trade_Creditors_Amount = ISNULL(@TotalAmount, 0)    --Net Invoice Total
    		SET @Net_Purchase_Price = ISNULL(@NetAmount, 0)          --Net Before VAT
    		SET @Rebate_Disc_Amount = ISNULL(@RebateDisc, 0)         --Before VAT
    		SET @Other_Discount_Amount = ISNULL(@OtherDisc, 0)       --Before VAT
    		SET @VAT_Contol_Amount = ISNULL(@TaxTotal, 0)
    
        --> Set Sys_AB_Transaction_Types_ID for GL Trans
            IF @Transaction_Type = 9         --9 = Supplier Refund
                SET @ABTranTypeID = 6        --6 = Accounts Payable - Refund
            ELSE                             --8 = Supplier Invoice
                SET @ABTranTypeID = 5        --5 = Accounts Payable - Invoice
    
    		BEGIN 
    			BEGIN 
    				SELECT @SupplierName = LEFT(Supplier_Name, 30),
    			           @Use_Rebate_Disc = Use_Rebate_Discount_Control_Acc,
    					   @Use_Other_Disc = Use_Other_Discount_Control_Acc,
    					   @Rebate_Disc_GL_Acc_ID = AB_Rebate_Discount_Account_ID,
    					   @Other_Disc_GL_Acc_ID = AB_Other_Discounts_Account_ID
    				FROM AO_Suppliers 
    				WHERE AO_Suppliers_ID = @Suppliers_ID
    
    
                    SET @GLDescription = RTRIM(LTRIM(@SupplierName))
    
    
                --> Ensure the GL accounts are valid
                    IF @Use_Rebate_Disc <> 1 OR @Rebate_Disc_GL_Acc_ID IS NULL   -- 1 = YES
    					BEGIN 
    						SET @Rebate_Disc_GL_Acc_ID = @Purchases_GL_Acc_ID
    					END 
    
    				IF @Use_Other_Disc <> 1 OR @Other_Disc_GL_Acc_ID IS NULL    -- 1 = YES
    					BEGIN 
    						SET @Other_Disc_GL_Acc_ID = @Purchases_GL_Acc_ID
    					END 			
    			END
    
    
                --> 25/07/04 - Added GRVID in 'Comment' field in UI SaveGReceivedV and SaveGReturnedV
                --             to distinguish between tran source i.e. Supplier Invoice & GRV Invoice
                IF @AO_GRV_ID IS NOT NULL
                    BEGIN
                        IF @AO_GRV_ID > 0    --Then this is a GRV
                            BEGIN
                                SET @Comment = RTRIM(LTRIM(@Comment))
                                SET @LENSupplier = 50 - (LEN(@Comment) + 1)
                                SET @LENComment = LEN(@Comment) + 1
    
                                IF LEN(@SupplierName) > @LENSupplier
                                    BEGIN
                                        SET @SupplierName = LEFT(@SupplierName, @LENSupplier)
                                    END
    
                                SET @GLDescription = LEFT((@SupplierName + ' ' + @Comment), 50)
                            END
                    END
    
    
            --> Rebate Discount
    			BEGIN
    				IF @Rebate_Disc_Amount <> 0 
    					BEGIN
                            IF @Use_Rebate_Disc = 1    -- 1 = YES
    							BEGIN		
                                    SET @TempRebateDisc = (ISNULL(@Rebate_Disc_Amount, 0) * - 1)
    
                                --> Update Rebate Discount GL Account
    								EXEC sp_AB_Insert_GL_Transactions
                                            @GLDescription,
                                            @ABTranTypeID,
    										@Rebate_Disc_GL_Acc_ID,
                                            @Invoice_Date,
                                            @Invoice_No,
                                            @MonthsID,
                                            @YearsID,
                                            @New_Suppliers_Invoice_ID,
    										@TempRebateDisc,
                                            @UserID,
                                            @CompanyID
    				
    								SET @Net_Purchase_Price = ISNULL(@Net_Purchase_Price, 0) + ISNULL(@Rebate_Disc_Amount, 0)
    							END
    					END
    			END	
    	
            --> Other Discount	
    			BEGIN 
    				IF @Other_Discount_Amount <> 0 
    					BEGIN		
    						IF @Use_Other_Disc = 1    -- 1 = YES
    							BEGIN
                                    SET @TempOtherDisc = (ISNULL(@Other_Discount_Amount,0) * -1)
    												
                                    EXEC sp_AB_Insert_GL_Transactions
                                            @GLDescription,
                                            @ABTranTypeID,
                                            @Other_Disc_GL_Acc_ID,
                                            @Invoice_Date,
                                            @Invoice_No,
                                            @MonthsID,
                                            @YearsID,
                                            @New_Suppliers_Invoice_ID,
                                            @TempOtherDisc,
                                            @UserID,
                                            @CompanyID
    
    								SET @Net_Purchase_Price = ISNULL(@Net_Purchase_Price, 0) + ISNULL(@Other_Discount_Amount, 0)
    							END
    					END
    			END	

    
                -------------------------------------------------------
                -- NEW 2004.4.3 - SPLIT GRV to GL INVENTORY Accounts by Product Type
                -------------------------------------------------------
                IF @SplitCOSTypes = 1
                    BEGIN
                        ---------------------------------------------------------------------
                        --> NEW 2004.4.3 -  Post Product GRV to an INVENTORY GL Account by Product Type
                        ---------------------------------------------------------------------
                        DECLARE GRV_Cursor CURSOR FOR
                            (
                                SELECT t.[Description],
                                       SUM(d.Net_Amount)
                                FROM AO_GRV_Details d
                                    INNER JOIN AO_GRV h
                                        ON h.AO_GRV_ID = d.AO_GRV_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
                                      d.AO_GRV_ID = @AO_GRV_ID AND
                              --> Added check to exclude Levy products 2004.5.7 RGL 2012-10-23        
                                      p.Slu_AW_YesNo_Levy_Item = 0
                                GROUP BY t.[Description]
                            )
    
                    	OPEN GRV_Cursor
    
                    	FETCH NEXT FROM GRV_Cursor 
                    	INTO
                            @SplitGLAccount,
                            @GRVAmount
    
                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN
    
                            SET @GRVAmount = ROUND(@GRVAmount, 2)
                            SET @InventoryGLDescription = LEFT('INVENTORY - ' + @SplitGLAccount, 50)

                            ---------------------------------------------------------------------
                            --> Get the SPLIT GL INVENTORY AccountID
                            ---------------------------------------------------------------------
                            SET @GLInventoryID = 0
    
                            --> Get the SPLIT GL INVENTORY AccountID
                            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
                                  Slu_AW_Active_ID = 1
    
                            IF @GLInventoryID = 0
                                BEGIN
                                    ---------------------------------------------------------------------
                                    --> NEW 2004.4.3 -  Post GRV to an INVENTORY GL Account by Product Type
                                    ---------------------------------------------------------------------
                     				EXEC @GLInventoryID = sp_AB_Insert_System_GL_Account
                                                            @InventoryGLDescription,
                                                            7,
                                                            @UserID,
                                                            @CompanyID
                                END
    
       
                            --> Create GL TRANSACTION for SPLIT INVENTORY Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @GLDescription,
                                    @ABTranTypeID,
                                    @GLInventoryID,
                                    @Invoice_Date,
                                    @Invoice_No,
                                    @MonthsID,
                                    @YearsID,
                                    @New_Suppliers_Invoice_ID,
                                    @GRVAmount,
                                    @UserID,
                                    @CompanyID
    
    
                        	FETCH NEXT FROM GRV_Cursor 
                        	INTO
                                @SplitGLAccount,
                                @GRVAmount
    
                    	END
    
                    	CLOSE GRV_Cursor
    
                    	DEALLOCATE GRV_Cursor
                        ---------------------------------------------------------------------
                        
                        --###################################################################
                        --Do Levy transactions
                        DECLARE GRV_Cursor CURSOR FOR
                            (
                                SELECT p.GL_Purchases_ID,
                                       SUM(d.Net_Amount)
                                FROM AO_GRV_Details d
                                    INNER JOIN AO_GRV h
                                        ON h.AO_GRV_ID = d.AO_GRV_ID
                                    INNER JOIN AP_Products p
                                        ON d.AP_Products_ID = p.AP_Products_ID
                                WHERE d.AW_User_Companies_ID = @CompanyID AND
                                      d.AO_GRV_ID = @AO_GRV_ID AND
                                      p.Slu_AW_YesNo_Levy_Item = 1
                                GROUP BY p.GL_Purchases_ID
                            )
    
                    	OPEN GRV_Cursor
    
                    	FETCH NEXT FROM GRV_Cursor 
                    	INTO
                            @GLInventoryID,
                            @GRVAmount
    
                    	WHILE @@FETCH_STATUS = 0
                    	BEGIN   
       
                            --> Create GL TRANSACTION for SPLIT INVENTORY Control
                            EXEC sp_AB_Insert_GL_Transactions
                                    @GLDescription,
                                    @ABTranTypeID,
                                    @GLInventoryID,
                                    @Invoice_Date,
                                    @Invoice_No,
                                    @MonthsID,
                                    @YearsID,
                                    @New_Suppliers_Invoice_ID,
                                    @GRVAmount,
                                    @UserID,
                                    @CompanyID
    
    
                        	FETCH NEXT FROM GRV_Cursor 
                        	INTO
                                @GLInventoryID,
                                @GRVAmount
    
                    	END
    
                    	CLOSE GRV_Cursor
    
                    	DEALLOCATE GRV_Cursor
                        --###################################################################
                        --Do Levy transactions                                              
                        
                    END
                ELSE
                    -------------------------------------------------------
                    --> The DEFAULT Purchases/Inventory GL entry behaviour
                    -------------------------------------------------------
                    BEGIN
						--5.9 RGL 2013-06-19 Fixed Adjustment GL entries
						--> INSERT Purchases GL entry
            				EXEC sp_AB_Insert_GL_Transactions
									@GLDescription,
									@ABTranTypeID,
            						@Purchases_GL_Acc_ID,
									@Invoice_Date,
									@Invoice_No,
									@MonthsID,
									@YearsID,
									@New_Suppliers_Invoice_ID,
            						@Net_Purchase_Price,
									@UserID,
									@CompanyID
						
							DECLARE GRV_Cursor CURSOR FOR
								(
									SELECT p.GL_Purchases_ID,
										   SUM(d.Net_Amount)
									FROM AO_GRV_Details d
										INNER JOIN AO_GRV h
											ON h.AO_GRV_ID = d.AO_GRV_ID
										INNER JOIN AP_Products p
											ON d.AP_Products_ID = p.AP_Products_ID
									WHERE d.AW_User_Companies_ID = @CompanyID AND
										  d.AO_GRV_ID = @AO_GRV_ID AND
										  p.Slu_AW_YesNo_Levy_Item = 1
									Group by p.GL_Purchases_ID      
								)
	    
                    		OPEN GRV_Cursor
	    
                    		FETCH NEXT FROM GRV_Cursor 
                    		INTO
								@GLInventoryID,
								@GRVAmount
	    
                    		WHILE @@FETCH_STATUS = 0
                    		BEGIN
								If @GLInventoryID = 0
								  Set @GLInventoryID = @Purchases_GL_Acc_ID
	                              
								--> INSERT Purchases GL entry
								EXEC sp_AB_Insert_GL_Transactions
										@GLDescription,
										@ABTranTypeID,
										@GLInventoryID,
										@Invoice_Date,
										@Invoice_No,
										@MonthsID,
										@YearsID,
										@New_Suppliers_Invoice_ID,
										@GRVAmount,
										@UserID,
										@CompanyID
	   
	    
                        		FETCH NEXT FROM GRV_Cursor 
                        		INTO
									@GLInventoryID,
									@GRVAmount
	    
                    		END
	    
                    		CLOSE GRV_Cursor    
                    		DEALLOCATE GRV_Cursor
--GRV SET Fix                    	END
                    END
                    -------------------------------------------------------
    
    
            --> Double Entry REQUIRES ALL @Trade_Creditors_GL_Acc_ID amounts to be REVERSED
                SET @Trade_Creditors_Amount = (ISNULL(@Trade_Creditors_Amount, 0) * -1)
    
    
            --> Trade Creditors
    			EXEC sp_AB_Insert_GL_Transactions
                        @GLDescription,
                        @ABTranTypeID,
    		            @Trade_Creditors_GL_Acc_ID,
                        @Invoice_Date,
                        @Invoice_No,
                        @MonthsID,
                        @YearsID,
                        @New_Suppliers_Invoice_ID,
    		            @Trade_Creditors_Amount,
                        @UserID,
                        @CompanyID
    
    		END		
    
        --> VAT  Control
            IF @VAT_Contol_Amount <> 0 
        		BEGIN
        			EXEC sp_AB_Insert_GL_Transactions
                            @GLDescription,
                            @ABTranTypeID,
        					@VAT_GL_Acc_ID,
                            @Invoice_Date,
                            @Invoice_No,
                            @MonthsID,
                            @YearsID,
                            @New_Suppliers_Invoice_ID,
        					@VAT_Contol_Amount,
                            @UserID, @CompanyID
        		END
    	END

    COMMIT TRAN Save_Supplier_Invoice

RETURN @New_Suppliers_Invoice_ID
SET NOCOUNT OFF

GO

--6 Modify AC_Customers And AO_Suppliers
--1. Modify AC_Customers ADD AW_YesNo_Apply_Product_Levy
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AC_Customers' AND
        C.Name='AW_YesNo_Apply_Product_Levy'
) 
BEGIN
  ALTER TABLE AC_Customers ADD AW_YesNo_Apply_Product_Levy Tinyint NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Customers].[AW_YesNo_Apply_Product_Levy]'
  -------------------------------------------------------
  
END
GO
 
SET NOCOUNT ON 
GO 
UPDATE AC_Customers
SET AW_YesNo_Apply_Product_Levy = 1
Where AW_YesNo_Apply_Product_Levy IS NUll
GO
SET NOCOUNT OFF 
GO

--2. Modify AO_Suppliers ADD AW_YesNo_Apply_Product_Levy
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_Suppliers' AND
        C.Name='AW_YesNo_Apply_Product_Levy'
) 
BEGIN
  ALTER TABLE AO_Suppliers ADD AW_YesNo_Apply_Product_Levy Tinyint NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Suppliers].[AW_YesNo_Apply_Product_Levy]'
  -------------------------------------------------------
    
END
GO

SET NOCOUNT ON
GO
UPDATE AO_Suppliers
SET AW_YesNo_Apply_Product_Levy = 1
Where AW_YesNo_Apply_Product_Levy IS NUll
GO
SET NOCOUNT OFF 
GO

--3. Modify AC_Customers ADD AW_YesNo_Change_Doc_Details
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AC_Customers' AND
        C.Name='AW_YesNo_Change_Doc_Details'
) 
BEGIN
  ALTER TABLE AC_Customers ADD AW_YesNo_Change_Doc_Details Tinyint NULL
              
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Customers].[AW_YesNo_Change_Doc_Details]'
  -------------------------------------------------------
    
END
GO

SET NOCOUNT ON 
GO
UPDATE AC_Customers
SET AW_YesNo_Change_Doc_Details = 0
Where AW_YesNo_Change_Doc_Details IS NUll
GO
SET NOCOUNT OFF 

GO
--7 sp_AO_Supplier_Lups
/****** Object:  StoredProcedure [dbo].[sp_AO_Supplier_Lups]    Script Date: 07/08/2013 20:43:45 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Supplier_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Supplier_Lups]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------
--Description   :sp_AO_Supplier_Lups
--Purpose       :
--Functionality :
--Parameters    :
--Date          :2002/02/26
--Authors       :TB
--MODS          :15/08/02 - Added @Choice=13 - Supplier Bank from Slu_AW_Banks
--              :29/08/02 - Removed ORDER BY [Description] in 8 = Credit Terms
--              :               This displays confusing ASCII Collating order
--              :28/10/02 - Added @Choice=14 - Months from Slu_AW_Months and
--              :               @Choice=15 - Years from Slu_AW_Years
--              :03/10/03 - Added @Choice 16 = Users and @Choice 17 = ALL Suppliers
--              :09/10/03 - Added @Choice 18 = Sys_AO_Delivery_Methods
--              :13/12/04 - Excluded Payment Method 11 and 13 from @Choice 11
--              :           Supplier Payment Methods
--2004.3.5      :01/05/07 - Added @Choice 19 = Supplier E-mail Address
--2004.3.8      :22/01/08 - Added @Choice 20 and 21 - Supplier Types and Groups
--2004.4.7      :26/08/09 - Added @Choice 22 - Account Type
--              :18/09/09 - Changed Option 11 and INCLUDED 'Debit Order' (Lombard)
--              :           and 'Credit Card' (TB)
--2004.5.9 RL   :2013-07-08 Added @Choice 23 = Apply Product Levy
------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Supplier_Lups]
    (
        @Choice int,
    	@CompanyID int = 1
    )
AS

SET NOCOUNT ON

    BEGIN
    --> 1 Purchase Price Types ID
    	IF @Choice = 1
			SELECT Lup_AO_Purchase_Price_Types_ID AS [ID], 
			      [Description] AS [Purchase Price Type] 
			FROM Lup_AO_Purchase_Price_Types
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

    --> 2 Formulas
    	ELSE
    	IF @Choice = 2
    		SELECT AW_Formulas_ID AS [ID], 
    		      [Description] AS [Formulas] 
    		FROM AW_Formulas
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY [Description] ASC

    --> 3 GL Accounts
    	ELSE 
    	IF @Choice = 3
    		SELECT AB_Accounts_ID AS [ID], 
    		      [Description] AS [GL Account] 
    		FROM AB_Accounts
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY [Description] ASC
    	
    --> 4 Active
    	ELSE
    	IF @Choice = 4
    		SELECT Slu_AW_Active_ID AS [ID], 
    		      [Description] AS [Active] 
    		FROM Slu_AW_Active
    		ORDER BY [Description] ASC

    --> 5 Account Status
    	ELSE 
    	IF @Choice = 5
    		SELECT Sys_AC_Account_Status_ID AS [ID], 
    		      [Description] AS [Account Status] 
    		FROM Sys_AC_Account_Status
    		ORDER BY [Description] ASC
    	
    --> 6 Tax Codes
    	ELSE 
    	IF @Choice = 6
    		SELECT Sys_AW_Tax_Codes_ID AS [ID], 
    		      [Description] AS [Tax_Code] 
    		FROM Sys_AW_Tax_Codes
    		ORDER BY [Description] ASC
    	
    --> 7 Countries
    	ELSE 
    	IF @Choice = 7
    		SELECT Slu_AW_Countries_ID AS [ID], 
    		      [Description] AS [Country] 
    		FROM Slu_AW_Countries
    		ORDER BY [Description] ASC
    	
    --> 8 Credit Terms
    	ELSE
    	IF @Choice = 8
    		SELECT Slu_AW_Credit_Terms_ID AS [ID],
    		      [Description] As [Credit Terms] 
    		FROM Slu_AW_Credit_Terms
--    --> ORDER BY [Description] displays confusing ASCII Collating order
--    		ORDER BY [Description]  ASC
    
    --> 9 Actor2
    	ELSE
    	IF @Choice = 9	--'Actor2'
          	SELECT AW_Users_ID as ID,
                ISNULL(Firstname + ' ', '') + ISNULL(Surname, '') as [Actor2] 
        	FROM AW_Users 
        	WHERE AW_Users_ID <> 1
        	ORDER BY firstname,Surname ASC
    
    --> 10 Transaction Types
    	ELSE
    	IF @Choice = 10	
           	SELECT Sys_AW_Transaction_Types_ID as [ID], 
                  [Description] as [Transaction Type] 
        	FROM Sys_AW_Transaction_Types 
        	WHERE Sys_AW_Transaction_Types_ID = 6 OR
                  Sys_AW_Transaction_Types_ID = 8 OR
                  Sys_AW_Transaction_Types_ID = 9 OR
                  Sys_AW_Transaction_Types_ID = 10 OR
                  Sys_AW_Transaction_Types_ID = 12
            ORDER BY [Description] ASC
    
    --> 11 Payment Methods (from GL)
    	ELSE
    	IF @Choice = 11
--     		SELECT Sys_AW_Payment_Methods_ID as [ID],
--                 Description as [Description] 
--     		FROM Sys_AW_Payment_Methods 
--     		WHERE (Sys_AW_Payment_Methods_ID <> 4 AND 
--     			   Sys_AW_Payment_Methods_ID <> 5 AND
--     			   Sys_AW_Payment_Methods_ID <> 7 AND
--     			   Sys_AW_Payment_Methods_ID <> 8 AND
--     			   Sys_AW_Payment_Methods_ID <> 9 AND
--     			   Sys_AW_Payment_Methods_ID <> 10 AND
--     			   Sys_AW_Payment_Methods_ID <> 11 AND
--     			   Sys_AW_Payment_Methods_ID <> 13 )
--     		ORDER BY [Description] ASC 

    		SELECT Sys_AW_Payment_Methods_ID as [ID],
                   Description as [Description] 
    		FROM Sys_AW_Payment_Methods 
    		WHERE (Sys_AW_Payment_Methods_ID = 1 OR 
    			   Sys_AW_Payment_Methods_ID = 2 OR 
    			   Sys_AW_Payment_Methods_ID = 3 OR 
    			   Sys_AW_Payment_Methods_ID = 4 OR 
    			   Sys_AW_Payment_Methods_ID = 6 OR 
    			   Sys_AW_Payment_Methods_ID = 12)
    		ORDER BY [Description] ASC 
    
    --> 12 Company Bank Accounts
    	ELSE
    	IF @Choice = 12
    	   	SELECT AW_Company_Banks_ID as [ID],
                   Account_Name as [Account Name] 
    		FROM AW_Company_Banks
    		WHERE AW_User_Companies_ID = @CompanyID
    		ORDER BY Account_Name ASC

    --> 13 Supplier Bank Account
    	ELSE
    	IF @Choice = 13
    	   	SELECT Slu_AW_Banks_ID as [ID],
                  [Description] as [Bank Name] 
    		FROM Slu_AW_Banks
    		ORDER BY [Description]

        --> Months
    	ELSE
    	IF @Choice = 14
    		SELECT Slu_AW_Months_ID AS [ID],
                  [Description] AS [Months]
    		FROM Slu_AW_Months
    
    --> Years
    	ELSE 
    	IF @Choice = 15
    		SELECT Slu_AW_Years_ID AS [ID],
                  [Description] AS [Years]
    		FROM Slu_AW_Years

    --> Users
    	ELSE 
    	IF @Choice = 16
          	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

    --> ALL Suppliers
    	IF @Choice = 17    --> ALL Suppliers
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name AS [Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY Supplier_Name ASC

    --> Purchase Order Delivery Methods
    	ELSE 
    	IF @Choice = 18
    		SELECT Sys_AO_Delivery_Methods_ID AS [ID], 
    		      [Description] AS [Delivery Method] 
    		FROM Sys_AO_Delivery_Methods
    		ORDER BY [Description] ASC

    --> Supplier E-mail Address
    	ELSE 
    	IF @Choice = 19
    		SELECT ISNULL(Email_Address, '') AS [Email] 
    		FROM AO_Suppliers
            WHERE AO_Suppliers_ID = @CompanyID

    --> Supplier Types
        ELSE
    	IF @Choice = 20
			SELECT Lup_AO_Supplier_Types_ID AS [ID], 
			      [Description] AS [Supplier_Type] 
			FROM Lup_AO_Supplier_Types
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

    --> Supplier Groups
        ELSE
    	IF @Choice = 21
			SELECT Lup_AO_Supplier_Groups_ID AS [ID], 
			      [Description] AS [Supplier_Group] 
			FROM Lup_AO_Supplier_Groups
			WHERE AW_User_Companies_ID = @CompanyID
			ORDER BY [Description] ASC

	--> Account Types
        ELSE
        IF @Choice = 22
          	SELECT Sys_AC_Account_Types_ID AS [ID],
                  [Description] 
            FROM Sys_AC_Account_Types
            ORDER BY [Description]
            
	--> Apply Product Levy
		ELSE
        IF @Choice = 23    
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [Apply Product Levy]
            FROM Slu_AW_YesNo

    END 

SET NOCOUNT OFF

GO

--8 sp_AO_Select_Supplier_Catalog
/****** Object:  StoredProcedure [dbo].[sp_AO_Select_Supplier_Catalog]    Script Date: 07/08/2013 21:01:47 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Supplier_Catalog]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Supplier_Catalog]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AO_Select_Supplier_Catalog
--Purpose       :Select ONE Supplier_ID 
--Date          :2002/02/27
--Authors       :TB
--Version       :1.0.0
--MODS          :15/08/02 - Added fields for Supplier Bank Details in Catalog
--              :09/10/03 - Added Sys_AO_Delivery_Methods_ID
--2004.3.8      :22/01/08 - Added Lup_AO_Supplier_Types_ID
--              :           and Lup_AO_Supplier_Groups_ID
--2004.4.7      :26/08/09 - Added Sys_AC_Account_Types_ID
--2004.4.9 RL   :2013-07-08 - Added AW_YesNo_Apply_Product_Levy
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AO_Select_Supplier_Catalog]
    (
        @Supplier_ID int,
    	@CompanyID int 
    )

AS

SET NOCOUNT ON

    SELECT
        AO_Suppliers_ID AS [ID], 
        Supplier_Name AS [Supplier Name], 
        Supplier_Number AS [Supplier No], 
        Old_Code AS [Old Supplier No], 
        Lup_AO_Purchase_Price_Types_ID AS [Purchase Price Type], 
        Use_Supplier_Discount_Defaults AS [Use_Supplier_Discount_Defaults],
        AW_Trade_Discount_Formula_ID AS [Trade Discount Formula],
        AW_Rebate_Discount_Formula_ID AS [Rebate Discount Formula],
        AB_Other_Discounts_Account_ID AS [Other Disc GL Account], 
        AB_Rebate_Discount_Account_ID AS [Rebate Disc GL Account], 
        Use_Other_Discount_Control_Acc AS [Use_Other_Discount_Control_Acc],
        Use_Rebate_Discount_Control_Acc AS [Use_Rebate_Discount_Control_Acc],
        Start_Date AS [Start Date], 
        Credit_Limit AS [Credit Limit], 
        Slu_AW_Credit_Terms_ID AS [Credit Terms], 
        Default_Settlement_Discount AS [Settlement Disc],
        Supplier_Contact AS [Contact Name], 
        Slu_AW_Active_ID AS [Active], 
        Sys_AC_Account_Types_ID AS [Account Types],
        Sys_AC_Account_Status_ID AS [Account Status], 
        Sys_AW_Tax_Codes_ID AS [Tax Code], 
        Tax_Number AS [Tax Number], 
        Notes AS [Notes],
        Post_Box AS [Post Box], 
        Post_Office AS [Post Office], 
        Post_Code AS [Post Code], 
        Street_Address AS [Street Address], 
        Suburb AS Suburb, 
        City AS City, 
        Street_Post_Code AS [Street Code], 
        Slu_AW_Countries_ID AS Country, 
        Supplier_Telephone AS [Tel No], 
        Contact_Cellphone AS [Contact Cell], 
        Supplier_Fax AS [Fax No], 
        Web_Site_URL AS [Web Site URL], 
        Orders_URL AS [Orders URL], 
        Sys_AO_Delivery_Methods_ID AS [Orders Delivery], 
        Email_Address AS [E-mail Address],
        Account_Balance AS [Account Balance], 
        Date_Captured AS [Date Captured], 
        [User_ID] AS [User ID], 
        AW_User_Companies_ID AS [Company ID] ,
        Slu_AW_Active_ID AS [Status],
        Slu_AW_Banks_ID AS [Bank Name],
        Bank_Branch AS [Branch Name],
        Bank_Branch_Code AS [Branch Code],
        Account_Name AS [Account Name],
        Account_Number AS [Account Number],
        Lup_AO_Supplier_Types_ID AS [Supplier_Type],
        Lup_AO_Supplier_Groups_ID AS [Supplier_Group],
        AW_YesNo_Apply_Product_Levy As [Apply_Product_Levy]
    FROM AO_Suppliers 
    WHERE AO_Suppliers_ID = @Supplier_ID AND 
    	  AW_User_Companies_ID = @CompanyID


SET NOCOUNT OFF

GO

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

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

SET NOCOUNT ON

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

SET NOCOUNT OFF

GO

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ELSE
    IF @Choice = 44	--'SICC Codes'
      	SELECT AW_SICC_Codes_ID as [ID] , [Description]
        FROM AW_SICC_Codes 
        ORDER BY [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

END  
 
GO

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

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

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

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

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

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

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

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

--12 sp_AS_POS_Customers_Select
/****** Object:  StoredProcedure [dbo].[sp_AS_POS_Customers_Select]    Script Date: 07/08/2013 22:23:19 ******/
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
-------------------------------------------------------------------------------

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

    SET @sql = @sql + '   ORDER BY [Name] '

EXEC (@sql)

SET NOCOUNT OFF

GO

--13 sp_AO_Get_Supplier_Apply_Levy
/****** Object:  StoredProcedure [dbo].[sp_AO_Get_Supplier_Apply_Levy]    Script Date: 07/08/2013 23:18:19 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Get_Supplier_Apply_Levy]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Get_Supplier_Apply_Levy]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description	:sp_AO_Get_Supplier_Apply_Levy
--Purpose       :Gets Supplier Apply Product Levy Setting From @SupplierID
--              :
--Date			:2013-07-08
--Authors		:RL
--Version		:2004.5.9
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AO_Get_Supplier_Apply_Levy]
	(
        @SupplierID int,
        @Apply_Product_Levy bit OUTPUT
	)
AS

SET NOCOUNT ON

    SELECT @Apply_Product_Levy = AW_YesNo_Apply_Product_Levy
    FROM AO_Suppliers
    WHERE AO_Suppliers_ID = @SupplierID

SET NOCOUNT OFF

GO

--14 Modify AS_Transactions_Address_Detail
--1. Modify AS_Transactions_Address_Detail ADD Customer_Name, [Tax_Number] [varchar](16) NULL, 
--AW_YesNo_Delivery_Address, AW_YesNo_Invoice
--Update History Data
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='Customer_Name'
) 
BEGIN
	UPDATE AS_Transactions_Address_Detail
	SET Inv_Address1 = '',
		Inv_Address2 = '',
		Inv_City = '',
		Inv_Code = ''

	DELETE AS_Transactions_Address_Detail
	WHERE ISNULL(LTRIM(RTRIM(Delivery_Address)),'') = ''
	AND ISNULL(LTRIM(RTRIM(Delivery_Suburb)),'') = ''
	AND ISNULL(LTRIM(RTRIM(Delivery_City)),'') = ''
	AND ISNULL(LTRIM(RTRIM(Delivery_Post_Code)),'') = ''
	
	DELETE AS_Transactions_Address
	WHERE AS_Transactions_Address_Detail_ID NOT IN (SELECT AS_Transactions_Address_Detail_ID
													FROM AS_Transactions_Address_Detail)
	
END
GO

IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='Customer_Name'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD Customer_Name varchar(50)
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Customer_Name]'
  -------------------------------------------------------
END
GO
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='Tax_Number'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD Tax_Number varchar(16)
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Tax_Number]'
  -------------------------------------------------------
END
GO
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='AW_YesNo_Delivery_Address'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD AW_YesNo_Delivery_Address Tinyint NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Address_Detail].[AW_YesNo_Delivery_Address]'
  -------------------------------------------------------
END
GO
IF NOT EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AS_Transactions_Address_Detail' AND
        C.Name='AW_YesNo_Invoice'
) 
BEGIN
  ALTER TABLE AS_Transactions_Address_Detail ADD AW_YesNo_Invoice Tinyint NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Address_Detail].[AW_YesNo_Invoice]'
  -------------------------------------------------------
END
GO

--15 sp_AS_Transactions_Address_Insert Drop sp_AS_Insert_Transactions_Address
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Insert_Transactions_Address]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Insert_Transactions_Address]
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
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Insert]
    (	@Company_ID	int, 	    	
		@AC_Customers_ID	int,   
    	@AS_Transactions_ID int,
    	@Inv_Customer_Name varchar(50),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@Delivery_Address varchar(40),
		@Delivery_Suburb varchar(40),
		@Delivery_City varchar(30),
		@Delivery_Post_Code varchar(10),
		@User_ID	int
    )
AS 

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

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

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

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

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

	SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID
	FROM AS_Transactions_Address_Detail
	WHERE AC_Customers_ID = @AC_Customers_ID AND
		  Customer_Name = @Inv_Customer_Name AND
		  Inv_Address1 = @Inv_Address1 AND
		  Inv_Address2 = @Inv_Address2 AND
		  Inv_Code = @Inv_Code AND
		  Inv_City = @Inv_City AND
		  Tax_Number = @Inv_Tax_Number AND
		  Delivery_Address = @Delivery_Address AND
		  Delivery_Suburb = @Delivery_Suburb AND
		  Delivery_City = @Delivery_City AND
		  Delivery_Post_Code = @Delivery_Post_Code

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

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

SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Select
--Purpose       :Select address details used on Invoices
--Functionality :Select address details used on Invoices
--Date          :2013-01-02
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Select]
    (    	    	
    	@AS_Transactions_ID int
    )
AS 

	SET NOCOUNT ON

	IF EXISTS
		(
			SELECT 1
			FROM AS_Transactions_Address
			WHERE AS_Transactions_ID = @AS_Transactions_ID
		)
	BEGIN
		SELECT AS_Transactions_ID,
			   Customer_Name AS 'Customer_Name',
			   Inv_Address1 AS 'Inv_Address1',
			   Inv_Address2 AS 'Inv_Address2',
			   Inv_City AS 'Inv_City',
			   Inv_Code AS 'Inv_Code',		
			   Tax_Number As 'Tax_Number',	   
			   Delivery_Address AS 'Delivery_Address',
			   Delivery_Suburb AS 'Delivery_Suburb',
			   Delivery_City AS 'Delivery_City',
			   Delivery_Post_Code AS 'Delivery_Post_Code'
		FROM AS_Transactions_Address_Detail d
			INNER JOIN AS_Transactions_Address a 
				ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID	
		WHERE a.AS_Transactions_ID = @AS_Transactions_ID
	END
	ELSE
	BEGIN
		SELECT 
			0 AS 'AS_Transactions_ID',
			'' AS 'Customer_Name',
			'' AS 'Inv_Address1',
			'' AS 'Inv_Address2',
			'' AS 'Inv_City',
			'' AS 'Inv_Code',
			'' AS 'Tax_Number',			
			'' AS 'Delivery_Address',
			'' AS 'Delivery_Suburb',
			'' AS 'Delivery_City',
			'' AS 'Delivery_Post_Code'
	END
	
SET NOCOUNT OFF
	
GO

--17 sp_AS_Transactions_Address_Update
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
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Update]
    (    	    	
    	@AS_Transactions_Address_Detail_ID int,
    	@Inv_Customer_Name varchar(50),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@Delivery_Address varchar(40),
		@Delivery_Suburb varchar(40),
		@Delivery_City varchar(30),
		@Delivery_Post_Code varchar(10),
		@User_ID	int
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
    	@AW_YesNo_Delivery_Address int,
    	@AW_YesNo_Invoice int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 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	
	
	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	 
		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

--18 sp_AS_Select_Delivery_Address_Hist
/****** Object:  StoredProcedure [dbo].[sp_AS_Select_Delivery_Address_Hist]    Script Date: 07/12/2013 13:39:18 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_Delivery_Address_Hist]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_Delivery_Address_Hist]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AS_Select_Delivery_Address_Hist
--Purpose       :Select address details used by customer
--Functionality :Select address details used by customer
--Date          :2013-01-02
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Select_Delivery_Address_Hist]
    (    	    	
    	@AC_Customers_ID int
    )
AS 

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

GO

--19 Modified AW_Users Table 
--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='IsRecordsManager'
) 
BEGIN
  ALTER TABLE AW_Users ADD IsRecordsManager tinyint
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AW_Users].[IsRecordsManager]'
  -------------------------------------------------------
END
GO

SET NOCOUNT ON
GO
UPDATE AW_Users
SET IsRecordsManager = 1
GO
SET NOCOUNT OFF

GO

--20 sp_AS_Select_IsRecordsManager
/****** Object:  StoredProcedure [dbo].[sp_AS_Select_IsRecordsManager]    Script Date: 07/14/2013 22:46:21 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Select_IsRecordsManager]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Select_IsRecordsManager]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Select_IsRecordsManager
--Purpose       :Select if User is a Records Manager
--Date          :2013-07-14
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE Procedure [dbo].[sp_AS_Select_IsRecordsManager]
    (
        @UserID int,
        @IsRecordsManager tinyint OUTPUT
    )

AS

SET NOCOUNT ON


    SET @IsRecordsManager = 0

    SELECT @IsRecordsManager = IsRecordsManager
    FROM AW_Users
    WHERE AW_Users_ID = @UserID AND
          Slu_AW_Active_ID = 1

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

SET NOCOUNT OFF

GO

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

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     		

    END

SET NOCOUNT OFF

GO

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

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

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]
    FROM AW_Users 
    WHERE AW_Users_ID = @User_ID

SET NOCOUNT OFF

GO

--23 sp_AO_Select_Filtered_Products
/****** Object:  StoredProcedure [dbo].[sp_AO_Select_Filtered_Products]    Script Date: 07/15/2013 17:00:28 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Filtered_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Filtered_Products]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

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

AS

SET NOCOUNT ON


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



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

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

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

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

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

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


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


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

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

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

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


    SET @SQL = @SQL + @Criteria


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


    EXEC (@SQL)

SET NOCOUNT OFF

GO

--24 sp_RPT_AP_Inventory_Analysis
/****** Object:  StoredProcedure [dbo].[sp_RPT_AP_Inventory_Analysis]    Script Date: 07/15/2013 20:17:07 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Inventory_Analysis]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Inventory_Analysis]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Inventory_Analysis
--Purpose       :Retrieves Product Sales Usage Analysis for last 12 months
--Functionality :Uses TABLE datatype
--              :    Conditional upon:
--              :        Has_Sales OR
--              :        Has On_Hand <> 0 OR
--              :        Has Min_Stock_Level <> 0 OR
--              :        Has Min_Order_Qty <> 0 OR
--              :        Has Max_Order_Qty <> 0 OR
--              :        Has_Orders AND
--              :        IS Active
--Date          :2003/04/11
--Authors       :TB
--Version       :1.0.0
--MODS:         :01/05/03 - Modified WHERE clause bracket ALL the OR conditions
--              :           including SALES
--              :20/10/03 - Modified to improve execution speed by 25x by using
--              :           TempTable instead of correlated subquery
--              :23/10/03 - Modified to use TABLE datatype instead of a #TempTable
--              :           and now selects ORDERS from SALES instead of SALES
--              :           from ORDERS which improves execution speed a further 2x
--              :26/12/04 - Added AW_User_Companies_ID = @CompanyID - Was = 1
--2004.2.7      :20/02/05 - Added a WHERE filter to EXCLUDE INACTIVE products
--2004.3.4      :19/11/06 - Added SortOrder input parameter
--2004.3.5      :09/06/07 - Added NonStock input parameter
--2004.5.9 RL	:2013-07-15 Added Average_Cost, Price1_Price1, Price1_Price2 
--							For new report Invetory Analysis Condesed Report For Autoweil
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Inventory_Analysis]
    (
        @Filter varchar(30),
        @EndDate datetime,
        @SortOrder tinyint,
        @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),
        @chkNonStock tinyint = 1
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @StartDate datetime

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @EndDate = '2003/90/30 23:59:59'
-- SET @Jan = '012003'
-- SET @Feb = '022003'
-- SET @Mar = '032003'
-- SET @Apr = '042003'
-- SET @May = '052003'
-- SET @Jun = '062003'
-- SET @Jul = '072003'
-- SET @Aug = '082003'
-- SET @Sep = '092003'
-- SET @Oct = '102002'
-- SET @Nov = '112002'
-- SET @Dec = '122002'

    SET @StartDate = DATEADD(yy, -1, @EndDate)


    ---------------------------------------------
    --> NEW 23/10/03 using TABLE datatype
    ---------------------------------------------
    IF EXISTS (SELECT * FROM dbo.sysobjects
               WHERE id = object_id(N'[dbo].[AP_Products_Temp]') AND
                          OBJECTPROPERTY(id, N'IsUserTable') = 1)
        DROP TABLE [dbo].[AP_Products_Temp]

    DECLARE @ActiveProducts table
                (
                    [AP_Products_ID] int
                )

    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AS_Transaction_Details
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AO_Order_Details od
        INNER JOIN AO_Orders oh
            ON od.AO_Orders_ID = oh.AO_Orders_ID
    WHERE oh.AW_User_Companies_ID = @CompanyID AND
          oh.Slu_AW_Active_ID = 1 AND
          oh.Date_Ordered IS NOT NULL AND
          oh.Complete <> 1 AND
         (ISNULL(od.Order_Qty, 0) + ISNULL(od.Back_Order_Qty, 0) - ISNULL(od.Received_Qty, 0)) > 0
--      AND dbo.fn_AS_Product_Has_Sales(@CompanyID, @StartDate, @EndDate) = 1


    INSERT INTO @ActiveProducts
    SELECT DISTINCT AP_Products_ID
    FROM AP_Products
    WHERE AW_User_Companies_ID = @CompanyID AND
          Slu_AW_Active_ID = 1 AND
          (
              On_Hand <> 0 OR
              Min_Stock_Level <> 0 OR
              Min_Order_Qty <> 0 OR
              Max_Order_Qty <> 0
          )


    SELECT DISTINCT AP_Products_ID
    INTO AP_Products_Temp
    FROM @ActiveProducts
    ORDER BY AP_Products_ID

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


    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 = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Filter = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' ISNULL(p.[Description], '''') AS [Description], '
    SET @sql = @sql + ' ISNULL(p.Product_Code, '''') AS [Code], '
    SET @sql = @sql + ' ISNULL(p.On_Hand, 0) AS [OnHand], '
    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 + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0) - ISNULL(SUM(od.Received_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is not null AND '
    SET @sql = @sql + '           o.Complete <> 1 AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Orders], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT (ISNULL(SUM(od.Order_Qty), 0) + ISNULL(SUM(od.Back_Order_Qty), 0)) '
    SET @sql = @sql + '     FROM AO_Order_Details od '
    SET @sql = @sql + '         INNER JOIN AO_Orders o '
    SET @sql = @sql + '             ON od.AO_Orders_ID = o.AO_Orders_ID '
    SET @sql = @sql + '     WHERE o.Date_Ordered is null AND '
    SET @sql = @sql + '           od.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Pending], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '     SELECT SUM(oc.Qty) '
    SET @sql = @sql + '     FROM AO_Order_Candidates oc '
    SET @sql = @sql + '     WHERE oc.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' ), 0) AS [Basket], '

    SET @sql = @sql + ' p.Last_Cost AS [LastCost], '

	--RL 2013-07-15 Added Average_Cost, Price1_Price1, Price1_Price2 
	--For new report Invetory Analysis Condesed Report For Autoweil
    SET @sql = @sql + ' p.Average_Cost As [AverageCost], '
    SET @sql = @sql + ' p.Price1_Price1 As [Price1Price1], '
    SET @sql = @sql + ' p.Price1_Price2 As [Price1Price2], '

    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jan + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jan], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Feb + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Feb], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Mar + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Mar], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Apr + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Apr], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @May + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [May], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jun + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jun], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Jul + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Jul], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Aug + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Aug], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Sep + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Sep], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Oct + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Oct], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Nov + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Nov], '
    SET @sql = @sql + ' ISNULL(( '
    SET @sql = @sql + '    SELECT SUM(d.Quantity) '
    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 + '     WHERE d.AP_Products_ID = p.AP_Products_ID AND '
    SET @sql = @sql + '           dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) = ''' + @Dec + ''' AND '
    SET @sql = @sql + '          (h.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '           h.Sys_AW_Transaction_Types_ID = 4) '
    SET @sql = @sql + '     GROUP BY dbo.fn_AS_Get_MonthYear_Number(h.Transaction_Date) '
    SET @sql = @sql + ' ), 0) AS [Dec] '

    SET @sql = @sql + ' FROM AP_Products p '

---------------------------------------------
--> NEW 20/10/03
---------------------------------------------
    SET @sql = @sql +
        ' INNER JOIN AP_Products_Temp temp ' +
        '     ON p.AP_Products_ID = temp.AP_Products_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 = 'Sales Person'
        SET @sql = @sql +
            ' LEFT JOIN Lup_AS_Reps o ' +
            '     ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '


    SET @sql = @sql + ' WHERE p.Slu_AW_Active_ID = 1 '


    IF @chkNonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item = 0 '
        END


    IF @SortOrder = 0    --by Product Description
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Description] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Filter], [Code] '
        END


    --PRINT @sql

    EXEC (@sql)


---------------------------------------------
--> NEW 20/10/03
---------------------------------------------
    DROP TABLE AP_Products_Temp
---------------------------------------------
SET NOCOUNT OFF

GO

--25 Add new report Inventory Analysis Condensed

SET NOCOUNT ON
GO

    IF NOT EXISTS
        (
            SELECT Sys_AW_Reports_ID
            FROM Sys_AW_Reports
            WHERE Report_No = '222' AND
                  Method_Name = 'Show_InventoryAnalysisCondensed'
        ) 
        BEGIN
            INSERT 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',
                    '222',
                    'Inventory Analysis Condensed',
                    'Inventory Analysis Condensed',
                    'SpSProductReports',
                    'CInterface',
                    'Show_InventoryAnalysisCondensed'
                )
        END
GO

--26 Insert Barcode Options into Sys_AW_Options
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtBarCode'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtBarCode',
		0,
		2,
		Getdate(),
		1,
		1
	)
END
GO
--chkBarExcluseNoNStock
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarExcludeNoNStock'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkBarExcludeNoNStock',
		0,
		1,
		Getdate(),
		1,
		1
	)
END
GO
--chkBarOrdProductCode
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarOrdProductCode'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkBarOrdProductCode',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--chkBarcodeChecksum
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarcodeChecksum'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkBarcodeChecksum',
		0,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--chkBarcodeChecksum
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkPrintAfterGRV'
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'CheckBox',
		'chkPrintAfterGRV',
		1,
		0,
		Getdate(),
		1,
		1
	)
END
GO
--optBarLabelSize - 1
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'optBarLabelSize' AND
		Control_Index = 1
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'OptionButton',
		'optBarLabelSize',
		1,
		'False',
		Getdate(),
		1,
		1
	)
END
GO
--optBarLabelSize - 2
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'optBarLabelSize' AND
		Control_Index = 2
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'OptionButton',
		'optBarLabelSize',
		2,
		'False',
		Getdate(),
		1,
		1
	)
END
GO
--optBarLabelSize - 3
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'optBarLabelSize' AND
		Control_Index = 3
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'OptionButton',
		'optBarLabelSize',
		3,
		'True',
		Getdate(),
		1,
		1
	)
END
SET NOCOUNT OFF

GO

--27 sp_RPT_AP_Barcode_Labels_Print
/****** Object:  StoredProcedure [dbo].[sp_RPT_AP_Barcode_Labels_Print]    Script Date: 07/17/2013 08:51:11 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Barcode_Labels_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Barcode_Labels_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :[sp_RPT_AP_Barcode_Labels_Print]
--Purpose       :Barcode Labels Print
--Date          :2013/07/17
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AP_Barcode_Labels_Print]
	(
    	@CompanyID int,
    	@AP_Products_ID int,
    	@AO_GRV_ID int,
        @Qty int
	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(4000),
            @SQL varchar(4000),
            @NonStock int,
            @Sort int

	SET @Filter = ''
    SET @SQL = ''
	SET @NonStock = 0
	SET @Sort = 0
		
	SELECT @NonStock = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarExcludeNoNStock'

	SELECT @Sort = Control_Value
	FROM Sys_AW_Options
	WHERE Control_Name = 'chkBarOrdProductCode'

	IF @Filter = ''
    BEGIN
		SET @Filter = ' AND ' + ' 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

	IF @AP_Products_ID <> 0
	BEGIN
    	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 [Description], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' ''' + CONVERT(varchar(20), @Qty) + ''' AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        --SET @SQL = @SQL + ' WHERE p.AP_Products_ID = Cast( ''' + @AP_Products_ID + ''',varchar(10))'
        SET @SQL = @SQL + ' WHERE p.AP_Products_ID = ' + CONVERT(varchar(20), @AP_Products_ID) + ''
        SET @SQL = @SQL + ' AND IsNull(p.Slu_AW_YesNo_Levy_Item,0) = 0 '
       
        SET @SQL = @SQL + @Filter
    END    
	ELSE
	BEGIN
    	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 [Description], '
        SET @SQL = @SQL + ' p.Product_Code AS [ProductCode], '
        SET @SQL = @SQL + ' d.Qty AS [OnHand], '
        SET @sql = @sql + ' ISNULL(p.Product_Code, '''') '
        SET @sql = @sql + '     + '' ('' + CONVERT(varchar(10), p.AP_Products_ID) + '')'' AS [CompositeCode] '
        SET @SQL = @SQL + ' FROM AP_Products p '
        SET @SQL = @SQL + ' INNER JOIN AO_GRV_Details d ON '
        SET @SQL = @SQL + ' p.AP_Products_ID = d.AP_Products_ID '        
        SET @SQL = @SQL + ' INNER JOIN AO_GRV g ON '
        SET @SQL = @SQL + ' g.AO_GRV_ID = d.AO_GRV_ID '        
        --SET @SQL = @SQL + ' WHERE g.AO_GRV_ID = Cast( ''' + @AO_GRV_ID + ''' ,varchar(10)) +'
        SET @SQL = @SQL + ' WHERE g.AO_GRV_ID = ' + CONVERT(varchar(20), @AO_GRV_ID) +''
        SET @SQL = @SQL + ' AND IsNull(p.Slu_AW_YesNo_Levy_Item,0) = 0 '               
        SET @SQL = @SQL + @Filter		
	END
        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

--28 sp_AP_Product_Filter_Lups
/****** Object:  StoredProcedure [dbo].[sp_AP_Product_Filter_Lups]    Script Date: 07/23/2013 13:13:54 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Product_Filter_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Product_Filter_Lups]
GO

/****** Object:  StoredProcedure [dbo].[sp_AP_Product_Filter_Lups]    Script Date: 07/23/2013 13:13:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


---------------------------------------------------------------------------------
--Description   :sp_AP_Product_Filter_Lups
--Purpose       :Returns LUPS for Product Filters
--Functionality :
--Date          :2005/04/27
--Authors       :TB
--MODS          :21/10/05 - Added Options 8 = Location, 9 = Added Barcode Types
--2004.3.4      :27/03/07 - Added Added Options 10 = Purchase
--2004.5.7 RGL  :2012-10-20 - Added Product Levy 11
--2004.5.8 RGL  :2013-02-20 - Added <None> as Levy LU
---------------------------------------------------------------------------------
CREATE Procedure [dbo].[sp_AP_Product_Filter_Lups]
    (
    	@Option int,
    	@Company_ID int
    )
AS

SET NOCOUNT ON

        IF @Option = 1    --> 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] ASC
        
        ELSE
        IF @Option = 2    --> 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] ASC
        
        ELSE
        IF @Option = 3    --> 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] ASC
        
        ELSE
        IF @Option = 4    --> 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 = 5    --> 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] ASC
        
        ELSE
        IF @Option = 6    --> Active
        	SELECT Slu_AW_Active_ID AS [ID],
        		[Description] AS [Active]
        	FROM Slu_AW_Active
        
        ELSE
        IF @Option = 7    --> Yes No
          	SELECT Slu_AW_YesNo_ID AS [ID],
                [Description] AS [YesNo]
            FROM Slu_AW_YesNo

    	ELSE 
    	IF @Option = 8    --> 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] ASC

    	ELSE 
    	IF @Option = 9    --> Barcode Types
    		SELECT Sys_AW_Barcode_Types_ID AS [ID],
    		   [Type] AS [Barcode],
               [Value_ID],
               [Mnemonic],
               [Description]
    		FROM Sys_AW_Barcode_Types

    	ELSE 
    	IF @Option = 10    --> Purchase Category
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID],
    			[Description] AS [Purchase]
    		FROM Lup_AP_Purchase_Categories
            WHERE AW_User_Companies_ID = @Company_ID
            ORDER BY [Description] ASC
        ELSE    
    	IF @Option = 11    --> Levy   
    	    SELECT 0 AS [ID],
    		      '<None>' As [Levy]
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @Company_ID AND
    		   Slu_AW_YesNo_Levy_Item = 1            
            UNION        
            SELECT AP_Products_ID AS [ID],
    		      [Description] As [Levy]
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @Company_ID AND
    		   Slu_AW_YesNo_Levy_Item = 1
            ORDER BY 2 ASC

SET NOCOUNT OFF

GO

--29 sp_AP_Select_Products_Lups
/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Products_Lups]    Script Date: 07/23/2013 13:16:53 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Products_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Products_Lups]
GO

/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Products_Lups]    Script Date: 07/23/2013 13:16:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-----------------------------------------------------------------------------
--Description   :sp_AP_Select_Products_Lups
--Purpose       :Product Catalog Lookups
--Functionality :
--Parameters    :
--Date          :2001/11/13
--Authors       :TB
--MODS          :11/07/02 - Modified SORT ORDER of most LUPS to ALPHA
--2004.2.4      :23/10/05 - Modified Choice 17 and added ALIAS [Plu Tabs]
--              :           causing list field not displaying in Catalog 
--2004.3.4      :26/02/07 - Added Choice 18 as [Purchase Categories]
--2004.4.0      :25/07/07 - Added Choice 19 as [CostPlusGroup]
--2004.5.7 RGL	:2012-10-23 - Added 20 as Unit Weight and 21 as Product Levy
--2004.5.8 RGL  :2013-02-20 - Added <None> as Levy LU
-----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Select_Products_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 [Product Types] 
    		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 [Product Groups] 
    		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 [Product Departments] 
    		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 [Product Locations] 
    		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 [Product Manufacturer] 
    		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 [Default Supplier] 
    		FROM AO_Suppliers
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Supplier_Name]
    
    --> 7 - Units Of Measure
    	IF @Choice = 7
    		SELECT Slu_AP_Units_Of_Measure_ID AS [ID], 
    		[Description] AS [Units Of Measure] 
    		FROM Slu_AP_Units_Of_Measure
            ORDER BY [Description]
    
    --> 8 - Mass Codes
    	ELSE
    	IF @Choice = 8
    		SELECT Lup_AP_Mass_Codes_ID AS [ID],
    		[Description] As [Mass Codes] 
    		FROM Lup_AP_Mass_Codes
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 9 - Active
    	ELSE
    	IF @Choice = 9
    		SELECT Slu_AW_Active_ID AS [ID],
    		[Description] As [Status] 
    		FROM Slu_AW_Active
    
    --> 10 - AW YesNO
    	ELSE
    	IF @Choice = 10
    		SELECT Slu_AW_YesNo_ID AS [ID], 
    		[Description] AS [AW YesNo] 
    		FROM Slu_AW_YesNo
    
    --> 11 - Rounding Codes
    	ELSE
    	IF @Choice = 11
    		SELECT Lup_AP_Rounding_Codes_ID AS [ID],
    		[Description] As [Rounding Codes] 
    		FROM Lup_AP_Rounding_Codes		
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 12 - Tax Codes
    	ELSE
    	IF @Choice = 12
    		SELECT Sys_AW_Tax_Codes_ID AS [ID],
    		[Description] As [Tax Codes] 
    		FROM sys_AW_Tax_Codes
    
    --> 13 - Sales Discount Groups
    	ELSE
    	IF @Choice = 13
    		SELECT Lup_AP_Discount_Groups_ID AS [ID],
    		[Description] As [Discount Groups] 
    		FROM Lup_AP_Discount_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 14 - Sales Commissions Group
    	ELSE
    	IF @Choice = 14
    		SELECT Lup_AP_Commission_Groups_ID AS [ID],
    		[Description] As [Commissions Group] 
    		FROM Lup_AP_Commission_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 15 - Sell By Codes
    	ELSE
    	IF @Choice = 15
    		SELECT Lup_AP_Sell_By_Codes_ID AS [ID],
    		[Description] As [Sell By Codes] 
    		FROM Lup_AP_Sell_By_Codes
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    
    --> 16 - Formulas
    	ELSE
    	IF @Choice = 16
    		SELECT AW_Formulas_ID AS [ID],
    		[Description] As [Formulas] 
    		FROM AW_Formulas
    		WHERE AW_User_Companies_ID = @CompanyID
    
    --> 17 - PLU TAB Location
    	ELSE
    	IF @Choice = 17
    		SELECT Lup_AP_PLU_Tabs_ID AS [ID],
    		[Description] As [Plu Tabs] 
    		FROM Lup_AP_PLU_Tabs
    		WHERE AW_User_Companies_ID = @CompanyID

    --> 18 - Purchase Categories
    	ELSE 
    	IF @Choice = 18	
    		SELECT Lup_AP_Purchase_Categories_ID AS [ID], 
    		[Description] AS [Purchase Categories] 
    		FROM Lup_AP_Purchase_Categories	
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]

    --> 19 - Cost+Plus Groups
    	ELSE
    	IF @Choice = 19
    		SELECT Lup_AP_Markup_Groups_ID AS [ID],
    		[Description] As [CostPlusGroup] 
    		FROM Lup_AP_Markup_Groups
    		WHERE AW_User_Companies_ID = @CompanyID
            ORDER BY [Description]
    --> 20 - Unit Weight
    	ELSE
    	IF @Choice = 20
    		SELECT Lup_AP_AW_Weight_ID AS [ID],
    		[Description] As [Unit Weight] 
    		FROM Lup_AP_AW_Weight
            ORDER BY [Description]
    --> 21 - Levy Product
    	ELSE
    	IF @Choice = 21
			SELECT 0 AS [ID],
    		'<None>' As [Levy] 
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            UNION
    		SELECT AP_Products_ID AS [ID],
    		[Description] As [Levy]
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY 2

SET NOCOUNT OFF

GO

--30 sp_AS_POS_RPT_Invoice_Print
/****** Object:  StoredProcedure [dbo].[sp_AS_POS_RPT_Invoice_Print]    Script Date: 09/24/2012 05:28:57 ******/
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 OFF
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
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
    (
    	@TransactionID int
    )
AS

SET NOCOUNT ON

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

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

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

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

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

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

    SET @Message = ''

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

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

    IF @AC_Customers_ID <> 0
	BEGIN
		SELECT	@Customer_Name = REPLACE(ISNULL(Customer_Name, ''), '''', ''),
				@Inv_Address1 = REPLACE(ISNULL(Inv_Address1, ''), '''', ''),
				@Inv_Address2 = REPLACE(ISNULL(Inv_Address2, ''), '''', ''), 
				@Inv_City = REPLACE(ISNULL(Inv_City, ''), '''', ''),
				@Inv_Code = REPLACE(ISNULL(Inv_Code, ''), '''', ''),
				@Tax_Number = REPLACE(ISNULL(Tax_Number, ''), '''', ''),
				@AW_YesNo_Invoice = AW_YesNo_Invoice,
				@Delivery_Address = REPLACE(ISNULL(Delivery_Address, ''), '''', ''),
				@Delivery_Suburb = REPLACE(ISNULL(Delivery_Suburb, ''), '''', ''),
				@Delivery_City = REPLACE(ISNULL(Delivery_City, ''), '''', ''),
				@Delivery_Post_Code = REPLACE(ISNULL(Delivery_Post_Code, ''), '''', ''),
				@AW_YesNo_Delivery_Address = AW_YesNo_Delivery_Address
		FROM AS_Transactions_Address a
		INNER JOIN AS_Transactions_Address_Detail d ON 
			a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
		WHERE a.AS_Transactions_ID = @TransactionID
	END    
    --------------------------------------------------------------------

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

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

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

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

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

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

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

	IF @AW_YesNo_Invoice = 1
	BEGIN
      SET @sql = @sql + '''' + @Customer_Name + '''' + ' AS [CustomerName], '	  
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
		SET @sql = @sql + ' THEN RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') + '' / '' + IsNull(c.Firstnames,'''')'
		SET @sql = @sql + ' ELSE RTRIM(LTRIM(c.Surname)) + ISNULL('', '' + c.Initials, '''') '
		SET @sql = @sql + ' END AS [CustomerName], '
	END
	           	
    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
    --> POSTAL Address
	--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], '

	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

	--> STREET Address
	--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], '

	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

	--> DELIVERY Address
	--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], '

	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 + ' ISNULL(c.Customer_Number, '''') + ''('' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + '')'' AS [CustomerNo], '

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

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

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

    SET @sql = @sql + ' td.Discount_Amount AS [DetailDiscount] , '
    SET @sql = @sql + ' (td.Unit_Price * td.Quantity) + td.Discount_Amount AS [DetailAmount], '
    SET @sql = @sql + ' td.Tax_Amount AS [DetailTaxAmount], '
    SET @sql = @sql + ' td.Extended_Amount AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime], '
    SET @sql = @sql + ' u.UserName AS [UserCode], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Cell_No)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Home_Tel_No)), '''') AS [TelNos], '
	
	--> TAX Number
    --SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Tax_Number + '''' + ' AS [VATNo], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	END

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

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

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

    SET @sql = @sql +  '''' + @Message + '''' + ' AS [TextMessage], '
    SET @sql = @sql + ' @WhichAddress AS [AddressType], '
    SET @sql = @sql + ' td.Serial_No AS [SerialNo], '
    SET @sql = @sql + ' td.Make AS [Make], '
    SET @sql = @sql + ' td.Customer AS [Customer], '
    SET @sql = @sql + ' @WhichName AS [NameType], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Orders_URL)), '''') + '
    SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') + '
    SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') AS [Emails] '

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

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

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF

GO

--31 New Spiral Logos
--Document Logo
UPDATE 
	Sys_AW_Options
SET
	Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\New_SpiralsoftADV2.bmp'
WHERE 
	Control_Name = 'txtCompanyLogoPath' AND
	Control_Index = 0 AND
	Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Spiralsoft.bmp'
GO

--Logon & Main Screen, Left Logo - Image Value
IF Exists
(
	SELECT 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtLogoGraphic' AND
		Control_Index = 0 AND
		Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\SpiralsoftADV1.bmp'
)
BEGIN		
	--Logon & Main Screen, Left Logo - Image Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\New_SpiralsoftADV1.bmp'
	WHERE 
		Control_Name = 'txtLogoGraphic' AND
		Control_Index = 0 

	--Logon & Main Screen, Left Logo - Left Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = '100'
	WHERE 
		Control_Name = 'txtBannerLogoLeft' AND
		Control_Index = 0

	--Logon & Main Screen, Left Logo - Top Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = '300'
	WHERE 
		Control_Name = 'txtBannerLogoTop' AND
		Control_Index = 0

END
GO

--Logon & Main Screen, Right Logo - Image Value
IF Exists
(
	SELECT 1
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtLogoGraphic' AND
		Control_Index = 1 AND
		Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\Advantage550pixH.jpg'
)
BEGIN	
	--Logon & Main Screen, Right Logo - Image Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = 'C:\Program Files\Spiralsoft\Advantage\Graphics\New_SpiralsoftADV1.bmp'
	WHERE 
		Control_Name = 'txtLogoGraphic' AND
		Control_Index = 1 

	--Logon & Main Screen , Right Logo - Left Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = '12500'
	WHERE 
		Control_Name = 'txtBannerLogoLeft' AND
		Control_Index = 1

	--Logon & Main Screen , Right Logo - Top Value
	UPDATE 
		Sys_AW_Options
	SET
		Control_Value = '300'
	WHERE 
		Control_Name = 'txtBannerLogoTop' AND
		Control_Index = 1
END
GO

--32 sp_AP_Delete_NonActive_Products
/****** Object:  StoredProcedure [dbo].[sp_AP_Delete_NonActive_Products]    Script Date: 07/23/2013 23:39:28 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Delete_NonActive_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Delete_NonActive_Products]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Delete_NonActive_Products
--Purpose       :DELETE NON Active UNUSED Products with ZERO STOCK
--Functionality :    DELETE Product in AP_Products and all RELATED tables
--              :        WHERE no SALE and GRV and ORDER exists
--Date          :2013/07/23
--Authors       :RL
--MODS:         :
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

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

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

	DELETE AO_Order_Candidates_Temp
	WHERE AP_Products_ID = @ProductID

	DELETE AO_Supplier_Contracts
	WHERE AP_Products_ID = @ProductID

	DELETE AO_Supplier_Product_Discounts
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Inventory_Adjustments
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Product_Selling_Prices
	WHERE AP_Products_ID = @ProductID

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

	DELETE AP_Products_History
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Stock_Takes
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Suppliers
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Products_Switch3
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Promotion_Products
	WHERE AP_Products_ID = @ProductID

	DELETE AP_Stock_Exchange
	WHERE AP_Products_ID = @ProductID


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


END

SET NOCOUNT OFF

GO

--33
/****** Object:  StoredProcedure [dbo].[sp_AB_Insert_Journal_Detail]    Script Date: 07/30/2013 10:32:47 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Insert_Journal_Detail]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Insert_Journal_Detail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Insert_Journal_Detail
--Purpose       :Inserts a journal Detail
--              :NB: By Default also Inserts a GLTransaction record
--Functionality :Tables: AB_Journal_Details, sp_AB_Insert_GL_Transactions
--Parameters    :
--Date          :2002/02/04
--Authors       :TB
--Version       :1.0.0
--MODS          :05/02/02 - Parameterized the inserting of a GL Transaction
--              :29/12/02 - Added @JnlNarration and fetched from Journal Header
--              :           to seperate Gl Transaction notes from Journal notes
--              :17/10/03 - Replaced @New_Journal_Detail_ID with @JnlHeaderID:
--              :           Eliminates a new GL Tran Ref No each journal allocation
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :20/12/04 - Assigned the Journal_Reference value to @GLSourceRef now !!!
-- RL V5.9      :2013-07-30 - Increased notes length to 70
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Insert_Journal_Detail]
    (
    	@JnlHeaderID int,
    	@AB_Accounts_ID int,
    	@Amount money,
    	@Notes varchar(70),
    	@User_ID int,
        @Company_ID int,
        @InsertGLTran bit = 1
    )

AS

SET NOCOUNT ON

    DECLARE @New_Journal_Detail_ID int,
    		@Months_ID int, 
    		@Years_ID int,
            @JnlNarration varchar(50),
            @JnlDate datetime,
            @GLSourceRef varchar(20)

	BEGIN
		INSERT INTO AB_Journal_Details
			(
                AB_Journals_ID,
                AB_Accounts_ID,
                Amount,
                Notes,
                Date_Captured,
                [User_ID],
                AW_User_Companies_ID
            )
		VALUES 
			(
                @JnlHeaderID ,
                @AB_Accounts_ID ,
                @Amount,
                @Notes,
                getdate(),
                @User_ID ,
                @Company_ID
            )
	
		SELECT @New_Journal_Detail_ID = Scope_Identity() 
	END

    IF @InsertGLTran = 1    -- 1 = YES, 0 = NO 
    	BEGIN
    		SELECT @JnlNarration = LEFT(ISNULL(Journal_Narration, ''), 50),
                   @JnlDate = Journal_Date,
                   @GLSourceRef = LEFT(Journal_Reference, 20),
                   @Months_ID = ISNULL(Slu_AW_Months_ID, 0),
                   @Years_ID = ISNULL(Slu_AW_Years_ID, 0)
    		FROM AB_Journals
    		WHERE AB_Journals_ID = @JnlHeaderID


    		EXEC sp_AB_Insert_GL_Transactions
                    @JnlNarration,
                    15,
        			@AB_Accounts_ID,
                    @JnlDate,                --NEW
                    @GLSourceRef,            --NEW
                    @Months_ID,
                    @Years_ID,
                    @JnlHeaderID,
        			@Amount,
                    @User_ID,
                    @Company_ID	
    		    
    		RETURN @New_Journal_Detail_ID
    	END
	
SET NOCOUNT OFF

GO

--34
--1. Modify AB_Journal_Details Increase Notes field legth from 50 to 70
IF EXISTS
(
  SELECT * 
  FROM 
    SysObjects O INNER JOIN SysColumns C
  ON O.ID = C.ID
  WHERE ObjectProperty(O.ID,'IsUserTable') = 1 AND
        O.Name='AB_Journal_Details' AND
        C.Name='Notes'
) 
BEGIN
  ALTER TABLE AB_Journal_Details ALTER COLUMN Notes Varchar(70) NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Journal_Details].[Notes]'
  -------------------------------------------------------
  
END
GO

--35 sp_AS_POS_Customers_InvDel
/****** Object:  StoredProcedure [dbo].[sp_AS_POS_Customers_InvDel]    Script Date: 07/08/2013 22:23:19 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Customers_InvDel]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].sp_AS_POS_Customers_InvDel
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_InvDel
--Purpose       :POS Customer Invoice and Delivery Address Details
--Date          :2013/08/08
--Authors       :RL
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

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

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

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

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

	IF @WhichName = 1
		SET @sql = @sql + ' RTRIM(LTRIM(a.Surname)) + ISNULL('', '' + A.Initials, '''') + '' / '' + IsNull(A.Firstnames,'''') AS [CurrentInvName], '
	ELSE
		SET @sql = @sql + ' RTRIM(LTRIM(A.Surname)) + ISNULL('', '' + A.Initials, '''') AS [CurrentInvName], '	

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

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

SET NOCOUNT OFF

GO

--A1 sp_AB_9200
/****** Object:  StoredProcedure [dbo].[sp_AB_9200]    Script Date: 07/23/2013 12:54:18 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_9200]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_9200]
GO

/****** Object:  StoredProcedure [dbo].[sp_AB_9200]    Script Date: 07/23/2013 12:54:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_9200
--Purpose       :Cash Flow Forecast
--Date          :2010/06/19
--Authors       :TB
--MODS:
-------------------------------------------------------------------------------


CREATE             PROCEDURE [dbo].[sp_AB_9200]
    (
        @CompanyID int,
        @Option tinyint,
        @ExcludeInterCo tinyint,
        @MonthID int,
        @YearID int
    )

AS

SET NOCOUNT ON


    DECLARE @Now datetime,
            @EndPeriod varchar(6),
            @StartPeriod varchar(6),
            @CreditAccount tinyint,
            @LastPeriodProcedureDate datetime,
            @PriorPeriodProcedureDate datetime,
            @PrevPeriodProcedureDate datetime,
            @Opening money,
            @Receipts money,
            @Payments money,
            @MonthNo datetime,
            @YearNo datetime,
            @LastMonthID int,
            @LastYearID int


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


    SET @LastMonthID = @MonthID - 1
    SET @LastYearID = @YearID

    IF @LastMonthID = 0
        BEGIN
            SET @LastMonthID = 12
            SET @LastYearID = @LastYearID - 1
        END

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@LastMonthID, @LastYearID)
    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@MonthID, @YearID)
    SET @CreditAccount = 0

    -------------------------------------------------------------------------------
    --> Get Customer Account Type setting to determine credit status
    -------------------------------------------------------------------------------
    SELECT @CreditAccount = CONVERT(tinyint, ISNULL(Control_Value, '0'))
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkCreditAccountType' AND
          AW_User_Companies_ID = @CompanyID


    -------------------------------------------------------------------------------
    --> Get the date of the LAST CUSTOMER 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 
        BEGIN
    		SET @LastPeriodProcedureDate = '1900/01/01'
        END

    -------------------------------------------------------------------------------
    --> Get the date of the PRIOR CUSTOMER MONTH-END done
    -------------------------------------------------------------------------------
	SELECT TOP 1 @PriorPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PriorPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PriorPeriodProcedureDate = '1900/01/01'
        END

    -------------------------------------------------------------------------------
    --> Get the date of the PREVIOUS CUSTOMER MONTH-END done
    -------------------------------------------------------------------------------
	SELECT TOP 1 @PrevPeriodProcedureDate = Month_End_Date
	FROM AW_Period_Procedures 
	WHERE Sys_AW_Period_Procedure_Types_ID = 1 AND
          Month_End_Date <> @LastPeriodProcedureDate AND
          Month_End_Date <> @PriorPeriodProcedureDate
	ORDER BY Month_End_Date DESC


    --> Initialize M/E date if this is the FIRST Month-End procedure
	IF @PrevPeriodProcedureDate IS NULL 
        BEGIN
    		SET @PrevPeriodProcedureDate = '1900/01/01'
        END


    -------------------------------------------------------------------------------
    -- PROCEDURES
    -------------------------------------------------------------------------------


    --> LIST of ALL the CASH or OVERDRAFT Accounts - as at LAST MONTH END)
    ----------> Use: CASH ON HAND (beginning of month)
    IF @Option = 1
        BEGIN
            SELECT t.AB_Accounts_ID AS [GLID],
                   MAX(g.Description) AS [GLAccount],
                   ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [Balance]
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @StartPeriod
            GROUP BY t.AB_Accounts_ID
            ORDER BY [GLAccount]
        END


    --> LIST CB Receipts - GL Account Detail
    ----------> Use: CASH RECEIPTS (CURRENT month)
    ELSE
    IF @Option = 2
        BEGIN
            SELECT d.AB_Accounts_ID AS [GLID],
                   g.Description AS [GLAccount],
                   ISNULL(SUM(d.Amount), 0) AS [CBReceipt]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) < 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    --> LIST CB Payments - GL Account Detail
    ----------> Use: CASH PAID OUT (CURRENT month)
    ELSE
    IF @Option = 3
        BEGIN
            SELECT d.AB_Accounts_ID AS [GLID],
                   g.Description AS [GLAccount],
                   ISNULL(SUM(d.Amount), 0) AS [CBPayment]
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
--                  (g.Sys_AB_Account_Categories_ID <> 10 AND          -- Cash and Cash Equivalents
--                   g.Sys_AB_Account_Categories_ID <> 52) AND         -- Bank Overdraft
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) >= 0
            GROUP BY d.AB_Accounts_ID, g.Description
            ORDER BY [GLAccount]
        END


    --> UNION of OPTION 1 to 3
    ----------> Use: CASH POSITION (end of month)
    ELSE
    IF @Option = 4
        BEGIN
            SELECT @Opening = ISNULL(SUM(t.AB_Transaction_Amount), 0)
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @StartPeriod

            SELECT @Receipts = ISNULL(SUM(d.Amount), 0)
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) < 0

            SELECT @Payments = ISNULL(SUM(d.Amount), 0)
            FROM AB_Cash_Book_Transaction_Details d
                INNER JOIN AB_Cash_Book_Transactions h
                    ON d.AB_Cash_Book_Transactions_ID = h.AB_Cash_Book_Transactions_ID
                INNER JOIN AB_Accounts g
                    ON d.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE d.AW_User_Companies_ID = @companyID AND
--                  (g.Sys_AB_Account_Categories_ID <> 10 AND          -- Cash and Cash Equivalents
--                   g.Sys_AB_Account_Categories_ID <> 52) AND         -- Bank Overdraft
                  h.Slu_AW_Months_ID = @MonthID AND
                  h.Slu_AW_Years_ID = @YearID AND
                  ISNULL(d.Amount, 0) >= 0


-- PRINT CONVERT(varchar(30), @Opening)
-- PRINT CONVERT(varchar(30), @Receipts)
-- PRINT CONVERT(varchar(30), @Payments)
-- PRINT CONVERT(varchar(30), @Opening + @Receipts + @Payments)


            SELECT @Opening + @Receipts + @Payments AS [Closing]
        END



    --> LIST of ALL the CASH or OVERDRAFT Accounts - as at Now)
    ----------> Use: CASH ON HAND (beginning of month)
    IF @Option = 5
        BEGIN
            SELECT t.AB_Accounts_ID AS [GLID],
                   MAX(g.Description) AS [GLAccount],
                   ISNULL(SUM(t.AB_Transaction_Amount), 0) AS [Balance]
            FROM AB_GL_Transactions t
                INNER JOIN AB_Accounts g
                    ON t.AB_Accounts_ID = g.AB_Accounts_ID
            WHERE t.AW_User_Companies_ID = @CompanyID AND
                 (g.Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  g.Sys_AB_Account_Categories_ID = 52) AND      -- Bank Overdraft
                  dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= @EndPeriod
            GROUP BY t.AB_Accounts_ID
            ORDER BY [GLAccount]
        END


    --> TOTAL of ALL the CASH or OVERDRAFT Accounts - Now)
    IF @Option = 6
        BEGIN
            SELECT SUM(ISNULL(AB_Account_Balance, 0)) AS [Cash]
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  Sys_AB_Account_Categories_ID = 52)          -- Bank Overdraft
        END


    --> LIST of ALL the CASH or OVERDRAFT Accounts - Now)
    IF @Option = 7
        BEGIN
            SELECT AB_Accounts_ID AS [GLID],
                   Description AS [GLAccount],
                   ISNULL(AB_Account_Balance, 0) AS [Balance]
            FROM AB_Accounts
            WHERE AW_User_Companies_ID = @CompanyID AND
                 (Sys_AB_Account_Categories_ID = 10 OR        -- Cash and Cash Equivalents
                  Sys_AB_Account_Categories_ID = 52)          -- Bank Overdraft
            ORDER BY [GLAccount]
        END


    --> CASH Sales - Last Month
    ELSE
    IF @Option = 8
        BEGIN
            IF @CreditAccount = 1        --Using Account Type setting
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [CashSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Sys_AC_Account_Types_ID = 1 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
            ELSE                         --Using Credit Limit setting
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [CashSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Credit_Limit = 0 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
        END


    --> TOTAL Sales - Last Month
    ELSE
    IF @Option = 9
        BEGIN
            IF @ExcludeInterCo = 1            -- EXCLUDE Inter-Co
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [TotalSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                          c.Sys_AC_Account_Types_ID <> 3 AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
            ELSE                              -- INCLUDE Inter-Co
                BEGIN
                    SELECT ISNULL(SUM(t.Payment_Amount), 0) AS [TotalSales]
                    FROM AS_Transactions t
                        INNER JOIN AC_Customers c
                            ON t.AC_Customers_ID = c.AC_Customers_ID
                    WHERE t.AW_User_Companies_ID = @companyID AND
                         (t.Sys_AW_Transaction_Types_ID = 3 OR
                          t.Sys_AW_Transaction_Types_ID = 4) AND
                         (t.Date_Captured >= @PriorPeriodProcedureDate AND
                          t.Date_Captured <= @LastPeriodProcedureDate)
                END
        END


    --> TOTAL CB Receipts
    ELSE
    IF @Option = 10
        BEGIN
            SELECT ISNULL(SUM(Amount), 0) AS [CBReceipts]
            FROM AB_Cash_Book_Transactions
            WHERE AW_User_Companies_ID = @companyID AND
                  Slu_AW_Months_ID = @MonthID AND
                  Slu_AW_Years_ID = @YearID AND
                  ISNULL(Amount, 0) > 0
        END


    --> TOTAL CB Payments
    ELSE
    IF @Option = 11
        BEGIN
            SELECT ISNULL(SUM(Amount), 0) AS [CBPayments]
            FROM AB_Cash_Book_Transactions
            WHERE AW_User_Companies_ID = @companyID AND
                  Slu_AW_Months_ID = @MonthID AND
                  Slu_AW_Years_ID = @YearID AND
                  ISNULL(Amount, 0) < 0
        END

SET NOCOUNT OFF

GO

--A2 sp_AW_9990
/****** Object:  StoredProcedure [dbo].[sp_AW_9990]    Script Date: 07/23/2013 12:56:42 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9990]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9990]
GO

/****** Object:  StoredProcedure [dbo].[sp_AW_9990]    Script Date: 07/23/2013 12:56:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

---------------------------------------------------------------------------
-- NB NB NB NB NB NB ******************************************************
---------------------------------------------------------------------------

-- TRIGGER [dbo].[Ins_Lup_AP_Commission_Groups_ID]
-- TRIGGER [dbo].[Ins_Lup_AP_Product_Groups_ID]

-- MUST BE INSERTED MANUALLY BECAUSE IT CANNOT BE INSERTED IN A STORED PROC

---------------------------------------------------------------------------
-------------------------------------------------------------------------------
--Description   :sp_AW_9990
--Purpose       :Wipe all Products and Product Lookup table contents
--Tables        :     [AP_Inventory_Adjustments]
--              :     [AP_Inventory_Valuations]
--              :     [AP_Month_Sales_Actuals]
--              :     [AP_Month_Sales_Budgets]
--              :     [AP_Product_Selling_Prices]
--              :     [AP_Products]
--              :     [AP_Products_Assemblies]
--              :     [AP_Products_History]
--              :     [AP_Products_Stock_Takes]
--              :     [AP_Products_Suppliers]
--              :     [Lup_AP_Commission_Groups]
--              :     [Lup_AP_Discount_Groups]
--              :     [Lup_AP_Product_Departments]
--              :     [Lup_AP_Product_Groups]
--              :     [Lup_AP_Product_Locations]
--              :     [Lup_AP_Product_Manufacturers]
--              :     [Lup_AP_Product_Types]
--Parameters    :
--Date          :2002/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :07/01/03 - Refreshed with latest table defs
--              :18/10/03 - Refreshed with latest table defs
--              :20/12/03 - Refreshed with latest table defs
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.7      :29/08/07 - Refreshed with latest table defs - 2004.3.7
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                              PROCEDURE [dbo].[sp_AW_9990]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

BEGIN



    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].[FK_AP_Products_Static_Lup_AP_Product_Departments]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Departments

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Groups]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Groups

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Lup_AP_Product_Locations]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products] DROP CONSTRAINT FK_AP_Products_Lup_AP_Product_Locations

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Variable_Lup_AP_Product_Locations]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Variable] DROP CONSTRAINT FK_AP_Products_Variable_Lup_AP_Product_Locations

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Manufacturers]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Manufacturers

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Products_Static_Lup_AP_Product_Types]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Products_Static] DROP CONSTRAINT FK_AP_Products_Static_Lup_AP_Product_Types

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Ins_Lup_AP_Commission_Groups_ID]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
    drop trigger [dbo].[Ins_Lup_AP_Commission_Groups_ID]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Ins_Lup_AP_Discount_Groups_ID]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
    drop trigger [dbo].[Ins_Lup_AP_Discount_Groups_ID]

    
    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_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_Month_Sales_Actuals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Month_Sales_Actuals]

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

    
    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]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products]

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

    
    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_Static]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Static]

    
    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_Products_Suppliers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Suppliers]

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

    
    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_Transfers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfers]

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

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

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

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

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

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

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

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

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

    
    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_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_Month_Sales_Actuals] (
    	[AP_Month_Sales_Actuals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Calender_Year] [smallint] NOT NULL ,
    	[January] [money] NULL ,
    	[February] [money] NULL ,
    	[March] [money] NULL ,
    	[April] [money] NULL ,
    	[May] [money] NULL ,
    	[June] [money] NULL ,
    	[July] [money] NULL ,
    	[August] [money] NULL ,
    	[September] [money] NULL ,
    	[October] [money] NULL ,
    	[November] [money] NULL ,
    	[December] [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_Month_Sales_Budgets] (
    	[AP_Month_Sales_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Calender_Year] [smallint] NOT NULL ,
    	[January] [money] NULL ,
    	[February] [money] NULL ,
    	[March] [money] NULL ,
    	[April] [money] NULL ,
    	[May] [money] NULL ,
    	[June] [money] NULL ,
    	[July] [money] NULL ,
    	[August] [money] NULL ,
    	[September] [money] NULL ,
    	[October] [money] NULL ,
    	[November] [money] NULL ,
    	[December] [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_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] (
    	[AP_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Print_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SKU_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Measure] [decimal](9, 3) NULL ,
    	[Slu_AP_Units_Of_Measure_ID] [int] NULL ,
    	[Manufacturer_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Manufacturer_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Self_Managed] [tinyint] NULL ,
    	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Lup_AP_Product_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NULL ,
    	[Lup_AP_Sell_By_Codes_ID] [int] NULL ,
    	[Alternate_Code1] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Alternate_Code2] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supercession] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Last_Cost] [money] NOT NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Standard_Disc1] [decimal](7, 2) NULL ,
    	[Standard_Disc2] [decimal](7, 2) NULL ,
    	[Average_Markup] [decimal](8, 4) NULL ,
    	[Price1_Effective_Date] [datetime] NULL ,
    	[Price1_Price1] [money] NULL ,
    	[Price1_Price2] [money] NULL ,
    	[Price2_Effective_Date] [datetime] NULL ,
    	[Price2_Price1] [money] NULL ,
    	[Price2_Price2] [money] NULL ,
    	[Lup_AP_Rounding_Codes_ID] [int] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Lup_AP_Discount_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Commission_Groups_ID] [smallint] NULL ,
    	[Pack_Volume] [decimal](9, 3) NULL ,
    	[Lup_AP_Mass_Codes_ID] [int] NULL ,
    	[Pack_Mass] [decimal](9, 3) NULL ,
    	[Strength] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Quote_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Slu_AW_YesNo_Assembly] [tinyint] NULL ,
    	[Serial_Number] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Show_Image] [bit] NULL ,
    	[Image_File_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Edit_Price] [tinyint] NULL ,
    	[Slu_AW_YesNo_Edit_Discount] [tinyint] NULL ,
    	[Max_Discount_Perc] [decimal](5, 2) NULL ,
    	[Slu_AW_YesNo_Max_Discount_Perc] [tinyint] NULL ,
    	[Memo] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Keywords] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[PLU_Tab] [tinyint] NULL ,
    	[Slu_AW_YesNo_Non_Stock_Item] [tinyint] NULL ,
    	[GL_Purchases_ID] [int] NULL ,
    	[GL_Sales_ID] [int] NULL ,
    	[GL_COS_ID] [int] NULL ,
    	[Lup_AP_Purchase_Categories_ID] [int] NULL ,
    	[Lup_AP_Markup_Groups_ID] [smallint] NULL ,
    	[Slu_AW_YesNo_Cost_Plus_Item] [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]

    
    CREATE TABLE [dbo].[AP_Products_Assemblies] (
    	[AP_Products_Assemblies_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Parent_Product_ID] [int] NULL ,
    	[AP_Child_Product_ID] [int] NULL ,
    	[Units] [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].[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_Static] (
    	[AP_Products_Static_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[Print_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Keywords] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SKU_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Measure] [decimal](9, 3) NULL ,
    	[Slu_AP_Units_Of_Measure_ID] [int] NULL ,
    	[Manufacturer_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Manufacturer_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Lup_AP_Product_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Alternate_Code1] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Alternate_Code2] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supercession] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Volume] [decimal](9, 3) NULL ,
    	[Lup_AP_Mass_Codes_ID] [int] NULL ,
    	[Pack_Mass] [decimal](9, 3) NULL ,
    	[Strength] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Memo] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS 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 ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Count1] [decimal](9, 3) NULL ,
    	[Count2] [decimal](9, 3) NULL ,
    	[Count3] [decimal](9, 3) NULL ,
    	[Count4] [decimal](9, 3) NULL ,
    	[Total_Count] AS (isnull([Count1],0) + isnull([Count2],0) + isnull([Count3],0) + isnull([Count4],0)) ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    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 TABLE [dbo].[AP_Products_Variable] (
    	[AP_Products_Variable_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Lup_AP_Sell_By_Codes_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Average_Markup] [decimal](8, 4) NULL ,
    	[Price1_Effective_Date] [datetime] NULL ,
    	[Price1_Price1] [money] NULL ,
    	[Price1_Price2] [money] NULL ,
    	[Price2_Effective_Date] [datetime] NULL ,
    	[Price2_Price1] [money] NULL ,
    	[Price2_Price2] [money] NULL ,
    	[Lup_AP_Rounding_Codes_ID] [int] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Lup_AP_Discount_Groups_ID] [smallint] NULL ,
    	[Lup_AP_Commission_Groups_ID] [smallint] NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Quote_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Slu_AW_YesNo_Assembly] [tinyint] NULL ,
    	[Serial_Number] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Show_Image] [bit] NULL ,
    	[Image_File_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_YesNo_Edit_Price] [tinyint] NULL ,
    	[Slu_AW_YesNo_Edit_Discount] [tinyint] NULL ,
    	[Max_Discount_Perc] [decimal](5, 2) NULL ,
    	[Slu_AW_YesNo_Max_Discount_Perc] [tinyint] NULL ,
    	[PLU_Tab] [tinyint] NULL ,
    	[Slu_AW_YesNo_Non_Stock_Item] [tinyint] NULL ,
    	[Slu_AW_YesNo_Self_Managed] [tinyint] NULL ,
    	[GL_Purchases_ID] [int] NULL ,
    	[GL_Sales_ID] [int] 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_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 ,
    	[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] [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_Transfers] (
    	[AP_Stock_Transfers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Transfer_Date] [datetime] NULL ,
    	[Note] [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].[Lup_AP_Commission_Groups] (
    	[Lup_AP_Commission_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[Lup_AP_Discount_Groups] (
    	[Lup_AP_Discount_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[Lup_AP_PLU_Tabs] (
    	[Lup_AP_PLU_Tabs_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Tab_No] [tinyint] NULL ,
    	[Description] [varchar] (15) 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].[Lup_AP_Product_Departments] (
    	[Lup_AP_Product_Departments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Min_GP_Percentage] [decimal](7, 2) 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].[Lup_AP_Product_Groups] (
    	[Lup_AP_Product_Groups_ID] [smallint] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[Lup_AP_Product_Locations] (
    	[Lup_AP_Product_Locations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[Lup_AP_Product_Manufacturers] (
    	[Lup_AP_Product_Manufacturers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Old_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Supplier_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Lup_AP_Product_Types] (
    	[Lup_AP_Product_Types_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[Lup_AP_Purchase_Categories] (
    	[Lup_AP_Purchase_Categories_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [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].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Valuations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Valuations] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Valuations_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Month_Sales_Actuals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Month_Sales_Actuals] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Month_Sales_Actuals_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Month_Sales_Budgets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Month_Sales_Budgets] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Month_Sales_Budgets_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_History_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Inventory] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Inventory] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Inventory_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Static] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Static] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Static_ID]
    	)  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]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Variable] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Variable] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Variable_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	)  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]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Transfers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Transfers] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Transfers_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Commission_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Commission_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Commission_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Discount_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Discount_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Discount_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_PLU_Tabs] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_PLU_Tabs] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_PLU_Tabs_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Departments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Departments] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Departments_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Groups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Groups] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Groups_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Locations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Locations] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Locations_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Manufacturers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_AP_Product_Manufacturers] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Manufacturers_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Product_Types] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Product_Types] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Product_Types_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Lup_AP_Purchase_Categories] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Lup_Purchase_Categories] PRIMARY KEY  CLUSTERED 
    	(
    		[Lup_AP_Purchase_Categories_ID]
    	)  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter_Search] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Product_Selling_Prices] ON [dbo].[AP_Product_Selling_Prices]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Products_Assemblies_AP_Child_Product_ID] ON [dbo].[AP_Products_Assemblies]([AP_Child_Product_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Products_Suppliers_AP_Products_ID] ON [dbo].[AP_Products_Suppliers]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) ON [PRIMARY]

    
    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]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Filter_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Valuation_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Inventory_Adjustments_AP_Products_ID] ON [dbo].[AP_Inventory_Adjustments]([AP_Products_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Product_Selling_Prices] ADD 
    	CONSTRAINT [PK_AP_Product_Selling_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Product_Selling_Prices_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_AP_Products_Types_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Types_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_AP_Product_Manufacturers_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Manufacturers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Mass_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Mass_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AW_Tax_Codes_ID] ON [dbo].[AP_Products]([Sys_AW_Tax_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Rounding_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Rounding_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Sell_By_Codes_ID] ON [dbo].[AP_Products]([Lup_AP_Sell_By_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Locations_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Locations_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Departments_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Departments_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Product_Groups_ID] ON [dbo].[AP_Products]([Lup_AP_Product_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Units_Of_Measure_ID] ON [dbo].[AP_Products]([Slu_AP_Units_Of_Measure_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Lup_AP_Discount_Groups_ID] ON [dbo].[AP_Products]([Lup_AP_Discount_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Product_Code] ON [dbo].[AP_Products]([Product_Code]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Products_Assemblies] ADD 
    	CONSTRAINT [PK_AP_Products_Assemblies] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Products_Assemblies_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_Assemblies_AP_Parent_Product_ID] ON [dbo].[AP_Products_Assemblies]([AP_Parent_Product_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_History_AP_Products_ID] ON [dbo].[AP_Products_History]([AP_Products_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_AP_Products_Static_ID] ON [dbo].[AP_Products_Inventory]([AP_Products_Static_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_Date_Updated] ON [dbo].[AP_Products_Inventory]([Date_Updated]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Product_Code] ON [dbo].[AP_Products_Static]([Product_Code]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Description] ON [dbo].[AP_Products_Static]([Description]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_AP_Product_Manufacturers_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Manufacturers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Manufacturer_Code] ON [dbo].[AP_Products_Static]([Manufacturer_Code]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Lup_AP_Product_Departments_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Departments_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Lup_AP_Product_Groups_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_AP_Products_Static_Lup_AP_Product_Types_ID] ON [dbo].[AP_Products_Static]([Lup_AP_Product_Types_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Static_Date_Updated] ON [dbo].[AP_Products_Static]([Date_Updated]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Stock_Takes_AP_Products_ID] ON [dbo].[AP_Products_Stock_Takes]([AP_Products_ID]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Products_Suppliers] ADD 
    	CONSTRAINT [PK_AP_Products_Suppliers] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Products_Suppliers_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_Suppliers_AO_Suppliers_ID] ON [dbo].[AP_Products_Suppliers]([AO_Suppliers_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_AP_Products_Static_ID] ON [dbo].[AP_Products_Variable]([AP_Products_Static_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AW_Tax_Codes_ID] ON [dbo].[AP_Products_Variable]([Sys_AW_Tax_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Rounding_Codes_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Rounding_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Sell_By_Codes_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Sell_By_Codes_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Product_Locations_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Product_Locations_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Lup_AP_Discount_Groups_ID] ON [dbo].[AP_Products_Variable]([Lup_AP_Discount_Groups_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Variable_Date_Updated] ON [dbo].[AP_Products_Variable]([Date_Updated]) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	)  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) ON [PRIMARY]

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Stock_Exchange_AP_Products_ID] ON [dbo].[AP_Stock_Exchange]([AP_Products_ID]) ON [PRIMARY]

    
    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_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'

    
    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_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_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]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[April]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[August]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Month_Sales_Actuals].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[Calender_Year]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Month_Sales_Actuals].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[December]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[February]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[January]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[July]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[June]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[March]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[May]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[November]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[October]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Actuals].[September]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Month_Sales_Actuals].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Month_Sales_Actuals].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[April]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[August]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Month_Sales_Budgets].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[Calender_Year]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Month_Sales_Budgets].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[December]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[February]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[January]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[July]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[June]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[March]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[May]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[November]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[October]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Month_Sales_Budgets].[September]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Month_Sales_Budgets].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Month_Sales_Budgets].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Product_Selling_Prices].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Date_Captured]'

    
    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_Active]', N'[AP_Product_Selling_Prices].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Product_Selling_Prices].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Average_Markup]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Description]', N'[AP_Products].[Description]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_COS_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_Purchases_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[GL_Sales_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Commission_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Discount_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Markup_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Mass_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Departments_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Locations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Manufacturers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Product_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Purchase_Categories_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Rounding_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_Sell_By_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Measure]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Pack_Mass]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Pack_Size]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Pack_Volume]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Service_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Show_Image]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AP_Units_Of_Measure_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Assembly]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Cost_Plus_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AW_YesNo_Edit_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Slu_AW_YesNo_Edit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Non_Stock_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Self_Managed]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Disc1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Standard_Disc2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Assemblies].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Assemblies].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Assemblies].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Assemblies].[Units]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Assemblies].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_History].[AW_User_Companies_ID]'

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

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Inventory].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Inventory].[Date_Captured]'

    
    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_Active]', N'[AP_Products_Inventory].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Inventory].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Static].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Static].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Static].[Date_Updated]'

    
    EXEC sp_bindefault N'[dbo].[df_Description]', N'[AP_Products_Static].[Description]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Mass_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Departments_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Manufacturers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Lup_AP_Product_Types_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Measure]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Pack_Mass]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Pack_Size]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Static].[Pack_Volume]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Static].[Slu_AP_Units_Of_Measure_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Static].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Static].[User_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].[Count4]'

    
    setuser

    
    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_User_Companies]', N'[AP_Products_Suppliers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Suppliers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[Lead_Time]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Suppliers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Suppliers].[Trade_Disc_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Suppliers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Average_Markup]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Variable].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Variable].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Commission_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Discount_Groups_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Product_Locations_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Rounding_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Lup_AP_Sell_By_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price1_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price1_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price2_Price1]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Price2_Price2]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Quote_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Service_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Show_Image]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Variable].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Assembly]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Slu_AW_YesNo_Edit_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Slu_AW_YesNo_Edit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Max_Discount_Perc]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Non_Stock_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Slu_AW_YesNo_Self_Managed]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Variable].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Variable].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Variable].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'

    
    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_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'

    
    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_User_ID]', N'[AP_Stock_Exchange].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Take_Procedures].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Take_Procedures].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Take_Procedures].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Take_Procedures].[Stock_Valuation]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Take_Procedures].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Stock_Transfers].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Average_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Quantity]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Transfers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Standard_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfers].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Commission_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Commission_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Commission_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Commission_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Discount_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Discount_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Discount_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Discount_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_PLU_Tabs].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_PLU_Tabs].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_PLU_Tabs].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_PLU_Tabs].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Departments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Departments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[Lup_AP_Product_Departments].[Min_GP_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Departments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Departments].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Groups].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Groups].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Groups].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Groups].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Locations].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Locations].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Locations].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Locations].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Manufacturers].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Manufacturers].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Lup_AP_Product_Manufacturers].[Default_Supplier_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Manufacturers].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Manufacturers].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Product_Types].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Product_Types].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Product_Types].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Product_Types].[User_ID]'

    
    setuser

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_Purchase_Categories].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_Purchase_Categories].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_Purchase_Categories].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_Purchase_Categories].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AP_Products] ADD 
    	CONSTRAINT [FK_AP_Products_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Mass_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Mass_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Mass_Codes] (
    		[Lup_AP_Mass_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Product_Locations] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Locations_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Locations] (
    		[Lup_AP_Product_Locations_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Rounding_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Rounding_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Rounding_Codes] (
    		[Lup_AP_Rounding_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Sell_By_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Sell_By_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Sell_By_Codes] (
    		[Lup_AP_Sell_By_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AP_Unit_Types] FOREIGN KEY 
    	(
    		[Slu_AP_Units_Of_Measure_ID]
    	) REFERENCES [dbo].[Slu_AP_Units_Of_Measure] (
    		[Slu_AP_Units_Of_Measure_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Lup_AW_Tax_Codes] FOREIGN KEY 
    	(
    		[Sys_AW_Tax_Codes_ID]
    	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
    		[Sys_AW_Tax_Codes_ID]
    	)

    
    ALTER TABLE [dbo].[AP_Products_Static] ADD 
    	CONSTRAINT [FK_AP_Products_Static_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Mass_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Mass_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Mass_Codes] (
    		[Lup_AP_Mass_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Departments] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Departments_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Departments] (
    		[Lup_AP_Product_Departments_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Groups] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Groups_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Groups] (
    		[Lup_AP_Product_Groups_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Manufacturers] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Manufacturers_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Manufacturers] (
    		[Lup_AP_Product_Manufacturers_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Lup_AP_Product_Types] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Types_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Types] (
    		[Lup_AP_Product_Types_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Static_Slu_AP_Units_Of_Measures] FOREIGN KEY 
    	(
    		[Slu_AP_Units_Of_Measure_ID]
    	) REFERENCES [dbo].[Slu_AP_Units_Of_Measure] (
    		[Slu_AP_Units_Of_Measure_ID]
    	)

    
    ALTER TABLE [dbo].[AP_Products_Variable] ADD 
    	CONSTRAINT [FK_AP_Products_Variable_AW_User_Companies] FOREIGN KEY 
    	(
    		[AW_User_Companies_ID]
    	) REFERENCES [dbo].[AW_User_Companies] (
    		[AW_User_Companies_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Product_Locations] FOREIGN KEY 
    	(
    		[Lup_AP_Product_Locations_ID]
    	) REFERENCES [dbo].[Lup_AP_Product_Locations] (
    		[Lup_AP_Product_Locations_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Rounding_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Rounding_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Rounding_Codes] (
    		[Lup_AP_Rounding_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AP_Sell_By_Codes] FOREIGN KEY 
    	(
    		[Lup_AP_Sell_By_Codes_ID]
    	) REFERENCES [dbo].[Lup_AP_Sell_By_Codes] (
    		[Lup_AP_Sell_By_Codes_ID]
    	),
    	CONSTRAINT [FK_AP_Products_Variable_Lup_AW_Tax_Codes] FOREIGN KEY 
    	(
    		[Sys_AW_Tax_Codes_ID]
    	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
    		[Sys_AW_Tax_Codes_ID]
    	)

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

    SET ANSI_NULLS ON 

    
    
    
    
    -- -------------------------------------------------------------------------------
    -- --Description   : Ins_Lup_AP_Commission_Groups_ID
    -- --Purpose       : Cartesian Product Insert
    -- --              : for a newly added Lup_AP_Commission_Groups record into
    -- --              : AS_Commission_Categories_Groups
    -- --Functionality : Tables: Lup_AP_Commission_Groups_ID, Lup_AS_Commission_Categories_ID
    -- --Parameters    : 
    -- --Date          : 2002/02/04
    -- --Authors       : TB
    -- --Version       : 1.0.0
    -- -------------------------------------------------------------------------------
    -- 
    -- CREATE TRIGGER  Ins_Lup_AP_Commission_Groups_ID 
    --     ON Lup_AP_Commission_Groups
    -- 
    -- FOR INSERT
    -- 
    -- AS
    -- 
    -- SET NOCOUNT ON
    -- 
    -- 	INSERT AS_Commission_Categories_Groups
    --         (
    --             Lup_AP_Commission_Groups_ID,
    --             Lup_AS_Commission_Categories_ID
    --         )
    --     SELECT i.Lup_AP_Commission_Groups_ID,
    --            dc.Lup_AS_Commission_Categories_ID
    --     FROM Inserted i
    --         CROSS JOIN Lup_AS_Commission_Categories dc
    -- 
    -- SET NOCOUNT OFF
    -- 
    -- 
    -- 
    -- 
    -- GO
    -- SET QUOTED_IDENTIFIER OFF 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO
    -- 
    -- SET QUOTED_IDENTIFIER ON 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO
    -- 
    -- 
    -- 
    -- 
    -- 
    -- -------------------------------------------------------------------------------
    -- --Description   : Ins_Lup_AP_Discount_Groups_ID
    -- --Purpose       : Cartesian Product Insert
    -- --              : for a newly added Lup_AC_Discount_Categories record into
    -- --              : AS_Discount_Categories_Groups
    -- --Functionality : Tables: Lup_AP_Discount_Groups_ID, Lup_AC_Discount_Categories_ID
    -- --Parameters    : 
    -- --Date          : 2002/02/04
    -- --Authors       : TB
    -- --Version       : 1.0.0
    -- -------------------------------------------------------------------------------
    -- 
    -- CREATE TRIGGER  Ins_Lup_AP_Discount_Groups_ID
    --     ON Lup_AP_Discount_Groups
    -- 
    -- FOR INSERT
    -- 
    -- AS
    -- 
    -- SET NOCOUNT ON
    -- 
    -- 	INSERT AS_Discount_Categories_Groups
    --         (
    --             Lup_AP_Discount_Groups_ID,
    --             Lup_AC_Discount_Categories_ID
    --         )
    --     SELECT i.Lup_AP_Discount_Groups_ID,
    --            dc.Lup_AC_Discount_Categories_ID
    --     FROM Inserted i
    --         CROSS JOIN Lup_AC_Discount_Categories dc
    -- 
    -- SET NOCOUNT OFF
    -- 
    -- 
    -- 
    -- 
    -- 
    -- GO
    -- SET QUOTED_IDENTIFIER OFF 
    -- GO
    -- SET ANSI_NULLS ON 
    -- GO












    ---------------------------------------
    -- INSERT a RECORD into Lookups
    ---------------------------------------

    INSERT Lup_AP_Product_Departments
        (
            Description,
            Old_Code
        )
        VALUES
        (
            '<None>',
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Locations
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Manufacturers
        (
            Description,
            Old_Code
        )
        VALUES
        (
            '<None>',
            '<None>'
        )
    
    
    INSERT Lup_AP_Product_Types
        (
            Description
        )
        VALUES
        (
            '<None>'
        )
    
    
    INSERT Lup_AP_Commission_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )


    INSERT Lup_AP_Discount_Groups
        (
            Description
        )
        VALUES
        (
            '<None>'
        )


    INSERT AP_Products
        (
            Description,
            Print_Description,
            Product_Code,
            SKU_Code
        )
        VALUES
        (
            '<None>',
            '<None>',
            '000',
            '000'
        )


    SET @ReturnValue = 1

END

RETURN @ReturnValue
SET NOCOUNT OFF

GO

--A3 sp_AW_9991
/****** Object:  StoredProcedure [dbo].[sp_AW_9991]    Script Date: 07/23/2013 12:58:10 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9991]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9991]
GO

/****** Object:  StoredProcedure [dbo].[sp_AW_9991]    Script Date: 07/23/2013 12:58:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9991
--Purpose       :Wipe all General Ledger and GL Lookup table contents
--Tables        :     [AB_Accounts]
--              :     [AB_Control_Accounts]
--              :     [Lup_AB_Cost_Centers_ID]
--Parameters    :
--Date          :2002/08/12
--Authors       :TB
--Version       :1.0.0
--MODS          :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table
--              :26/12/02 - Added Recon_Amount field to AB_Cash_Book_Transactions
--              :27/12/02 - Replaced with 'Recurring_Number', int field with
--              :           Recurring_Reference, varchar(30) field
--              :03/01/02 - Added NEW AB_Budgets, and NEW columns to AB_Accounts
--              :07/01/03 - Refreshed with latest table defs
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.7      :02/10/07 - Refreshed with latest table defs - 2004.3.7
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                                PROCEDURE [dbo].[sp_AW_9991]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

    BEGIN
    
    
    
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_End_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_End_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_Start_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_Start_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Transactions_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_GL_Transactions] DROP CONSTRAINT FK_AB_Transactions_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Prior_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Month_Account_Actuals] DROP CONSTRAINT FK_AB_Prior_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Budget_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] DROP CONSTRAINT FK_AB_Budget_AB_Accounts

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Accounts]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Accounts

        
        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_Generator_Tabs_AB_Generator]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Columns] DROP CONSTRAINT FK_AB_Generator_Tabs_AB_Generator

        
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Generator_Rows_AB_Generator]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
        ALTER TABLE [dbo].[AB_Generator_Rows] DROP CONSTRAINT FK_AB_Generator_Rows_AB_Generator

        
        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_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Accounts]

        
        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_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_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_Generator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Generator]

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

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

        
        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_Month_Account_Actuals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AB_Month_Account_Actuals]

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

        
        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]

        
        CREATE TABLE [dbo].[AB_Accounts] (
        	[AB_Accounts_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 ,
        	[Sys_AB_Account_Categories_ID] [int] NULL ,
        	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
        	[Lup_AB_Cost_Centers_ID] [int] NULL ,
        	[Lup_AB_Account_Divisions_ID] [int] NULL ,
        	[Lup_AB_Account_Groups_ID] [int] NULL ,
        	[AB_Account_Balance] [money] NULL ,
        	[Opening_Balance] [money] NULL ,
        	[Opening_Date] [datetime] NULL ,
        	[Opening_Month] [tinyint] NULL ,
        	[Opening_Year] [int] NULL ,
        	[AW_YesNo_Controllable_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]

        
        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_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_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] (50) 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] (50) 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] (50) 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] (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_Generator] (
        	[AB_Generator_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Report_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Heading1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Heading2] [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_Generator_Columns] (
        	[AB_Generator_Tabs_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Generator_ID] [int] NULL ,
        	[Tab_Heading1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Heading2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Content_Type] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Period_Type] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Period_Extent] [tinyint] NULL ,
        	[Tab_Calc_Column1] [tinyint] NULL ,
        	[Tab_Operator] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Tab_Calc_Column2] [tinyint] NULL ,
        	[Tab_Format_Mask] [decimal](18, 0) 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_Generator_Rows] (
        	[AB_Generator_Rows_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Generator_ID] [int] NULL ,
        	[Row_Option] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Memo] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_AB_Start_Account_ID] [int] NULL ,
        	[Row_AB_End_Account_ID] [int] NULL ,
        	[Row_Alt_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_All_Accounts] [tinyint] NULL ,
        	[Row_Sum_All_Accounts] [tinyint] NULL ,
        	[Row_Calculation_Type] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Total_Level] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Total_Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_Total] [tinyint] NULL ,
        	[Row_Print_Percentages] [tinyint] NULL ,
        	[Row_Percentage_Types] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Row_Print_Prior] [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]

        
        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_Month_Account_Actuals] (
        	[AB_Actuals_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Accounts_ID] [int] NOT NULL ,
        	[Calender_Year] [smallint] NOT NULL ,
        	[January] [money] NULL ,
        	[February] [money] NULL ,
        	[March] [money] NULL ,
        	[April] [money] NULL ,
        	[May] [money] NULL ,
        	[June] [money] NULL ,
        	[July] [money] NULL ,
        	[August] [money] NULL ,
        	[September] [money] NULL ,
        	[October] [money] NULL ,
        	[November] [money] NULL ,
        	[December] [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_Month_Account_Budgets] (
        	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AB_Accounts_ID] [int] NOT NULL ,
        	[Calender_Year] [smallint] NOT NULL ,
        	[January] [money] NULL ,
        	[February] [money] NULL ,
        	[March] [money] NULL ,
        	[April] [money] NULL ,
        	[May] [money] NULL ,
        	[June] [money] NULL ,
        	[July] [money] NULL ,
        	[August] [money] NULL ,
        	[September] [money] NULL ,
        	[October] [money] NULL ,
        	[November] [money] NULL ,
        	[December] [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_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]

        
        ALTER TABLE [dbo].[AB_Accounts] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Accounts] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Accounts_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Budgets_ID]
        	)  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]
        	)  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]
        	)  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]
        	)  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] 

        
        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] 

        
        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] 

        
        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] 

        
        ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_GL_Transactions_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator_Columns] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator_Tabs] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_Tabs_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Generator_Rows] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Generator_Rows] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Generator_Rows_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Journal_Details_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Journals_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Month_Account_Actuals] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Month_Account_Actuals] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Actuals_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Month_Account_Budgets] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Budgets_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
        	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Recurring_ID]
        	)  ON [PRIMARY] 

        
        ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
        	(
        		[AB_Recurring_Details_ID]
        	)  ON [PRIMARY] 

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[AB_Account_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Accounts].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[AW_YesNo_Controllable_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Account_Divisions_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Account_Groups_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Lup_AB_Cost_Centers_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Balance]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Accounts].[Opening_Date]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Month]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Accounts].[Opening_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Accounts].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AB_Account_Categories_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Accounts].[Sys_AW_Tax_Codes_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Accounts].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Batches].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Batches].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Net_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Batches].[Slu_AW_Active_ID]'

        
        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_User_ID]', N'[AB_Cash_Book_Batches].[User_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[VAT_Amount]'

        
        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_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'

        
        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_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'

        
        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_User_ID]', N'[AB_Cash_Book_Transactions].[User_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_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator_Columns].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator_Columns].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator_Columns].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Calc_Column1]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Calc_Column2]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Format_Mask]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Columns].[Tab_Period_Extent]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator_Columns].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Generator_Rows].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Generator_Rows].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_All_Accounts]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Percentages]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Prior]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Print_Total]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Generator_Rows].[Row_Sum_All_Accounts]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Generator_Rows].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Generator_Rows].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[April]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[August]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Month_Account_Actuals].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[Calender_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Month_Account_Actuals].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[December]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[February]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[January]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[July]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[June]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[March]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[May]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[November]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[October]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Actuals].[September]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Month_Account_Actuals].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Month_Account_Actuals].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[April]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[August]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Month_Account_Budgets].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[Calender_Year]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Month_Account_Budgets].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[December]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[February]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[January]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[July]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[June]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[March]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[May]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[November]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[October]'

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Month_Account_Budgets].[September]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Month_Account_Budgets].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Month_Account_Budgets].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'

        
        setuser

        
        setuser

        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'

        
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'

        
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'

        
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'

        
        setuser

        
        ALTER TABLE [dbo].[AB_Accounts] ADD 
        	CONSTRAINT [FK_AB_Accounts_Lup_AB_Cost_Centers] FOREIGN KEY 
        	(
        		[Lup_AB_Cost_Centers_ID]
        	) REFERENCES [dbo].[Lup_AB_Cost_Centers] (
        		[Lup_AB_Cost_Centers_ID]
        	),
        	CONSTRAINT [FK_AB_Accounts_Lup_AW_Tax_Codes] FOREIGN KEY 
        	(
        		[Sys_AW_Tax_Codes_ID]
        	) REFERENCES [dbo].[Sys_AW_Tax_Codes] (
        		[Sys_AW_Tax_Codes_ID]
        	)

        
        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_Generator_Columns] ADD 
        	CONSTRAINT [FK_AB_Generator_Tabs_AB_Generator] FOREIGN KEY 
        	(
        		[AB_Generator_ID]
        	) REFERENCES [dbo].[AB_Generator] (
        		[AB_Generator_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Generator_Rows] ADD 
        	CONSTRAINT [FK_AB_Generator_Rows_AB_End_Accounts] FOREIGN KEY 
        	(
        		[Row_AB_End_Account_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	),
        	CONSTRAINT [FK_AB_Generator_Rows_AB_Generator] FOREIGN KEY 
        	(
        		[AB_Generator_ID]
        	) REFERENCES [dbo].[AB_Generator] (
        		[AB_Generator_ID]
        	),
        	CONSTRAINT [FK_AB_Generator_Rows_AB_Start_Accounts] FOREIGN KEY 
        	(
        		[Row_AB_Start_Account_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_Month_Account_Actuals] ADD 
        	CONSTRAINT [FK_AB_Prior_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_ID]
        	)

        
        ALTER TABLE [dbo].[AB_Month_Account_Budgets] ADD 
        	CONSTRAINT [FK_AB_Budget_AB_Accounts] FOREIGN KEY 
        	(
        		[AB_Accounts_ID]
        	) REFERENCES [dbo].[AB_Accounts] (
        		[AB_Accounts_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]
        	)




    
    
    
    
    
    
    
        ---------------------------------------
        -- INSERT a RECORD into Lookups
        ---------------------------------------
    
        INSERT Lup_AB_Cost_Centers
            (
                Description
            )
            VALUES
            (
                '<None>'
            )
    
    
        INSERT AB_Accounts
            (
                Description,
                Account_Number
            )
            VALUES
            (
                '<Select An Account>',
                '000-000'
            )
    
    
        ------------------------------------------------------------
        --Set ALL Control Accounts to the only record in AB_Accounts
        ------------------------------------------------------------
        UPDATE AB_Control_Accounts
        SET AB_Accounts_ID = 1
        ------------------------------------------------------------
    
    
    
        SET @ReturnValue = 1
    
    END

RETURN @ReturnValue
SET NOCOUNT OFF

GO

--A4 sp_AW_9992
/****** Object:  StoredProcedure [dbo].[sp_AW_9992]    Script Date: 07/23/2013 12:59:41 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9992]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9992]
GO

/****** Object:  StoredProcedure [dbo].[sp_AW_9992]    Script Date: 07/23/2013 12:59:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AW_9992
--Purpose       :Wipe Option table contents
--Tables        :     [Sys_AW_Options]
--Parameters    :
--Date          :2002/09/29
--Authors       :TB
--Version       :1.0.0
--MODS          :18/10/03 - Increased Control_Value to 250
--              :14/01/04 - Refreshed with latest table defs
--              :09/03/04 - Refreshed with latest table defs - ADV2004 - RC4
--              :20/07/04 - Refreshed with latest table defs - 2004.1.0
--2004.3.8      :04/05/08 - Refreshed with latest table defs - 2004.3.8
-------------------------------------------------------------------------------

CREATE                           PROCEDURE [dbo].[sp_AW_9992]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

BEGIN




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

    
    CREATE TABLE [dbo].[Sys_AW_Options] (
    	[Sys_AW_Options_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Control_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Control_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Control_Index] [smallint] NULL ,
    	[Control_Value] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[Sys_AW_Options] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Sys_AW_Options] PRIMARY KEY  CLUSTERED 
    	(
    		[Sys_AW_Options_ID]
    	)  ON [PRIMARY] 

    
    setuser

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Sys_AW_Options].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Sys_AW_Options].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Sys_AW_Options].[User_ID]'

    
    setuser











    SET @ReturnValue = 1

END

RETURN @ReturnValue

GO


--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------
IF NOT EXISTS
    (
        SELECT AA_Release_ID
        FROM AA_Release
        WHERE Release = '2004.5.9'
    )
    BEGIN
        INSERT AA_Release
            (
                Release,
                Updated_by			  
            )
        VALUES
            (
                '2004.5.9',
                'Download'
            )
    END
ELSE
    BEGIN
        UPDATE AA_Release
        SET Updated_by = 'Download',
            Date_Updated = getdate()
        WHERE Release = '2004.5.9'
    END   
    
GO    
