------------------------------------------------------------------------------
-- ADVANTAGE 2004.5.7
-- NEW OPTIONS, and minor bug fixes
-- 2012-11-05
-- RGL
------------------------------------------------------------------------------


--1. Modify Slu_AW_Countries 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='Slu_AW_Countries' AND
        C.Name='Country_Dialing_Code'
) 
BEGIN
  ALTER TABLE Slu_AW_Countries ADD Country_Dialing_Code Varchar(10) NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[Slu_AW_Countries].[Country_Dialing_Code]'
  -------------------------------------------------------
END
GO
        
UPDATE Sys_AW_Lookup_Editor
SET ColumnWidths = '0,3795,1470,1005,1005,1005,0,0,1005'
WHERE TableName = 'Slu_AW_Countries' 
GO

IF NOT EXISTS
(
  SELECT Sys_AW_Lookup_Editor_ID
  FROM Sys_AW_Lookup_Editor
  WHERE TableName = 'Slu_AW_Countries_Mobile' And
        Caption = 'Mobile Phone Dialing Codes'
)
BEGIN

  Declare @Sys_AW_Lookup_Editor_ID Int

  Set @Sys_AW_Lookup_Editor_ID = 0

  Select @Sys_AW_Lookup_Editor_ID = MAX(Sys_AW_Lookup_Editor_ID)
  From Sys_AW_Lookup_Editor

  Set @Sys_AW_Lookup_Editor_ID = @Sys_AW_Lookup_Editor_ID + 1

  INSERT Sys_AW_Lookup_Editor
  (
    Sys_AW_Lookup_Editor_ID,
    TableName,
    Caption,
    ColumnWidths
  )
  VALUES
  (
    @Sys_AW_Lookup_Editor_ID,
    'Slu_AW_Countries_Mobile',
    'Mobile Phone Dialing Codes',
    '0,7275,1005,1005,0,0,1005'
   )
END
GO
if exists (select * from dbo.sysobjects 
           where id = object_id(N'[dbo].[Slu_AW_Countries_Mobile]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Slu_AW_Countries_Mobile]
GO

CREATE TABLE [dbo].[Slu_AW_Countries_Mobile](
	[Slu_AW_Countries_Mobile_ID] [smallint] IDENTITY(1,1) NOT NULL,
    [Slu_AW_Countries_ID] [smallint] NOT NULL,	
	[Description] [varchar](50) NULL,
	[Mobile_Dialing_Code] [varchar](10) NULL,
	[Date_Captured] [datetime] NULL,
	[User_ID] [int] NULL,
	[Touched] [timestamp] NULL,
	[Slu_AW_Active_ID] [tinyint] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Slu_AW_Countries_Mobile] WITH NOCHECK ADD 
	CONSTRAINT [PK_Slu_AW_Countries_Mobile] PRIMARY KEY  CLUSTERED 
	(
		[Slu_AW_Countries_Mobile_ID]
	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
GO

 CREATE  INDEX [IX_Slu_AW_Countries_ID] ON [dbo].[Slu_AW_Countries_Mobile]([Slu_AW_Countries_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
GO

setuser
GO


IF NOT EXISTS
(
  SELECT 1
  FROM Slu_AW_Countries_Mobile
  WHERE Slu_AW_Countries_Mobile_ID = 1
)
BEGIN
  INSERT INTO Slu_AW_Countries_Mobile
  (
    Slu_AW_Countries_ID,
    Description,
    Mobile_Dialing_Code,
    Date_Captured,
    User_ID,
    Slu_AW_Active_ID  
  )
  VALUES
  (
    1,
    '<None>',
    'NA',
    GetDate(),
    -1,
    1
  )
END
Go

IF NOT EXISTS
(
  SELECT 1
  FROM Slu_AW_Countries_Mobile
  WHERE Slu_AW_Countries_ID = 193
  AND Mobile_Dialing_Code = '07' 
)
BEGIN
  INSERT INTO Slu_AW_Countries_Mobile
  (
    Slu_AW_Countries_ID,
    Description,
    Mobile_Dialing_Code,
    Date_Captured,
    User_ID,
    Slu_AW_Active_ID  
  )
  VALUES
  (
    193,
    '07 Prefix',
    '07',
    GetDate(),
    -1,
    1
  )
END
Go

IF NOT EXISTS
(
  SELECT 1
  FROM Slu_AW_Countries_Mobile
  WHERE Slu_AW_Countries_ID = 193
  AND Mobile_Dialing_Code = '08' 
)
BEGIN
  INSERT INTO Slu_AW_Countries_Mobile
  (
    Slu_AW_Countries_ID,
    Description,
    Mobile_Dialing_Code,
    Date_Captured,
    User_ID,
    Slu_AW_Active_ID  
  )
  VALUES
  (
    193,
    '08 Prefix',
    '08',
    GetDate(),
    -1,
    1
  )
END
Go

IF NOT EXISTS
(
  SELECT 1
  FROM Slu_AW_Countries_Mobile
  WHERE Slu_AW_Countries_ID = 13
  AND Mobile_Dialing_Code = '04' 
)
BEGIN
  INSERT INTO Slu_AW_Countries_Mobile
  (
    Slu_AW_Countries_ID,
    Description,
    Mobile_Dialing_Code,
    Date_Captured,
    User_ID,
    Slu_AW_Active_ID  
  )
  VALUES
  (
    13,
    '04 Prefix',
    '04',
    GetDate(),
    -1,
    1
  )
END
Go

IF NOT EXISTS
(
  SELECT 1
  FROM Slu_AW_Countries_Mobile
  WHERE Slu_AW_Countries_ID = 13
  AND Mobile_Dialing_Code = '05' 
)
BEGIN
  INSERT INTO Slu_AW_Countries_Mobile
  (
    Slu_AW_Countries_ID,
    Description,
    Mobile_Dialing_Code,
    Date_Captured,
    User_ID,
    Slu_AW_Active_ID  
  )
  VALUES
  (
    13,
    '05 Prefix',
    '05',
    GetDate(),
    -1,
    1
  )
END
Go
Update AW_Users
Set IsController = 1
Where AW_Users_ID = 1
Go

Update Slu_AW_Countries
Set Country_Dialing_Code = '27'
Where Description = 'SOUTH AFRICA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '244'
Where Description = 'ANGOLA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '61'
Where Description = 'AUSTRALIA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '267'
Where Description = 'BOTSWANA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '233'
Where Description = 'GHANA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '353'
Where Description = 'IRELAND'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '254'
Where Description = 'KENYA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '266'
Where Description = 'LESOTHO'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '261'
Where Description = 'MADAGASCAR'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '230'
Where Description = 'MAURITIUS'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '258'
Where Description = 'MOZAMBIQUE'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '64'
Where Description = 'NEW ZEALAND'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '234'
Where Description = 'NIGERIA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '250'
Where Description = 'RWANDA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '268'
Where Description = 'SWAZILAND'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '255'
Where Description = 'UNITED REPUBLIC OF TANZANIA'
Go
Update Slu_AW_Countries
Set Description = 'TANZANIA'
Where Description = 'UNITED REPUBLIC OF TANZANIA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '216'
Where Description = 'TUNISIA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '256'
Where Description = 'UGANDA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '44'
Where Description = 'UNITED KINGDOM'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '1'
Where Description = 'UNITED STATES OF AMERICA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '243'
Where Description = 'ZAIRE'
Go
Update Slu_AW_Countries
Set Description = 'Democratic Republic of the Congo'
Where Description = 'ZAIRE'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '260'
Where Description = 'ZAMBIA'
Go
Update Slu_AW_Countries
Set Country_Dialing_Code = '263'
Where Description = 'ZIMBABWE'
Go
--------------------------------------------------------------------------------
-- Functions 
--------------------------------------------------------------------------------

if exists (select * 
           from dbo.sysobjects 
           where id = object_id(N'[dbo].[fn_AO_Supplier_Period_Procedure_Ageing_Values]') 
           and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_AO_Supplier_Period_Procedure_Ageing_Values]
GO
-------------------------------------------------------------------------------
--Description   :fn_AO_Supplier_Period_Procedure_Ageing_Values
--Purpose       :Retrieves Supplier Ageing Amounts between each Age Area PERIODS
--              :    for Supplier Period Procedure
--Calls         :fn_AO_Supplier_Procedure_Period_Ageing
--Date          :2007/03/06
--Authors       :TB
--MODS          :
--              :RL 2012/05/09 - Changed @AgeTable Days (30 - 180) definition from 
--                            datetime to varchar(6)
-------------------------------------------------------------------------------
Create                         FUNCTION [dbo].[fn_AO_Supplier_Period_Procedure_Ageing_Values]
    (
        @SupplierID int,
        @ProcedureDate datetime,
        @MonthID int,
        @YearID int,
        @D1 varchar(6),
        @D2 varchar(6),
        @D3 varchar(6),
        @D4 varchar(6),
        @D5 varchar(6),
        @D6 varchar(6),
        @D7 varchar(6)
    )

RETURNS @AgeTable TABLE 
    (
    	SupplierID int,
    	Payment money,
    	Amount money,
    	[Current] money,
    	[30 Days] money,
    	[60 Days] money,
    	[90 Days] money,
    	[120 Days] money, 
    	[150 Days] money,
    	[180+ Days] money,
        CurrentDate datetime,
        Days30Date varchar(6),
        Days60Date varchar(6),
        Days90Date varchar(6),
        Days120Date varchar(6),
        Days150Date varchar(6),
        Days180Date varchar(6)
    )

AS
    BEGIN
    
        INSERT @AgeTable
        SELECT SupplierID,
            SUM([Payment]) AS [Payment],
            SUM([Amount]) AS [Amount],        
            SUM([Current]) AS [Current],
            SUM([30 Days]) AS [30 Days],
            SUM([60 Days]) AS [60 Days],
            SUM([90 Days]) AS [90 Days],
            SUM([120 Days]) AS [120 Days], 
            SUM([150 Days]) AS [150 Days],
            SUM([180+ Days]) AS [180+ Days],
            @ProcedureDate AS CurrentDate,
            @D1 AS Days30Date,
            @D2 AS Days60Date,
            @D3 AS Days90Date,
            @D4 AS Days120Date,
            @D5 AS Days150Date,
            @D6 AS Days180Date
--        FROM dbo.fn_AO_Supplier_Period_Procedure_Ageing_Non_Grouped
        FROM fn_AO_Supplier_Procedure_Period_Ageing
            (
                @SupplierID,
                @ProcedureDate,
                @MonthID,
                @YearID,
                @D1,
                @D2,
                @D3,
                @D4,
                @D5,
                @D6,
                @D7
            )
        GROUP BY SupplierID
    
    RETURN
    
    END
GO

--------------------------------------------------------------------------------
-- Stored Procedures
--------------------------------------------------------------------------------

/****** Object:  StoredProcedure [dbo].[sp_AA_DB_Size_Ver]    Script Date: 10/02/2012 08:26:04 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AA_DB_Size_Ver]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AA_DB_Size_Ver]
GO

/****** Object:  StoredProcedure [dbo].[sp_AA_DB_Size_Ver]    Script Date: 10/02/2012 08:26:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE          PROCEDURE [dbo].[sp_AA_DB_Size_Ver]
    (
            @DB_Name varchar(50),
            @Msg            varchar(500)     OUTPUT
    )
AS

SET NOCOUNT ON

Declare @DB_Size        int,
        @DB_Version     varchar(20)         

Set @Msg = ''

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

SELECT @DB_Version = Cast( SERVERPROPERTY('productversion') As Varchar)

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

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

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

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

Select @Msg

SET NOCOUNT OFF
Go


/****** Object:  StoredProcedure [dbo].[sp_AB_1120]    Script Date: 10/02/2012 08:29:01 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_1120]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_1120]
GO

/****** Object:  StoredProcedure [dbo].[sp_AB_1120]    Script Date: 10/02/2012 08:29:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------
--Description   :sp_AB_1120
--Purpose       :GL BUDGET GENERATOR 2
--Functionality :UPDATES THE BUDGET FOR ONE GL ACCOUNT
--Date          :2002/12/18
--Authors       :TB
--MODS:         :
--2004.5.5      :10/11/11 - Added [User_ID] field in the INSERT section
--2004.5.6      :11/01/12 - Reworked to return @RetCode return paramnter
-------------------------------------------------------------------------------
CREATE               PROCEDURE [dbo].[sp_AB_1120]
    (
    	@GLAccountID int,
        @YearID int,
        @MonthID tinyint,
    	@Amount money,
        @CompanyID int,
        @UserID int
    )
AS

SET NOCOUNT ON

    DECLARE @RetCode int

    SET @RetCode = 0

--     IF EXISTS
--         (
--             SELECT AB_Budgets_ID
--             FROM AB_Budgets
--             WHERE AB_Accounts_ID = @GLAccountID AND
--                   Slu_AW_Years_ID = @YearID AND
--                   Slu_AW_Months_ID = @MonthID AND
--                   AW_User_Companies_ID = @CompanyID
-- 
--         )
--         BEGIN
--             UPDATE AB_Budgets
--             SET Budget_Amount = @Amount,
--                 [User_ID] = @UserID
--             WHERE AB_Accounts_ID = @GLAccountID AND
--                   Slu_AW_Years_ID = @YearID AND
--                   Slu_AW_Months_ID = @MonthID AND
--                   AW_User_Companies_ID = @CompanyID
--         END


    SELECT @RetCode = AB_Budgets_ID
    FROM AB_Budgets
    WHERE AB_Accounts_ID = @GLAccountID AND
          Slu_AW_Years_ID = @YearID AND
          Slu_AW_Months_ID = @MonthID AND
          AW_User_Companies_ID = @CompanyID

    IF @RetCode = 0
        BEGIN
            INSERT AB_Budgets
                (
                    AB_Accounts_ID,
                    Slu_AW_Years_ID,
                    Slu_AW_Months_ID,
                    Budget_Amount,
                    [User_ID],
                    AW_User_Companies_ID
                )
            VALUES
                (
                	@GLAccountID,
                    @YearID,
                    @MonthID,
                	@Amount,
                    @UserID,
                    @CompanyID
                )

            SELECT @RetCode = Scope_Identity()
        END
    ELSE
        BEGIN
            UPDATE AB_Budgets
            SET Budget_Amount = @Amount,
                [User_ID] = @UserID
            WHERE AB_Budgets_ID = @RetCode
        END

RETURN @RetCode

GO

/****** Object:  StoredProcedure [dbo].[sp_AB_Annual_Budget_Export]    Script Date: 10/02/2012 08:30:18 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Annual_Budget_Export]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Annual_Budget_Export]
GO

/****** Object:  StoredProcedure [dbo].[sp_AB_Annual_Budget_Export]    Script Date: 10/02/2012 08:30:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Annual_Budget_Export
--Purpose       :Annual Budget Export
--Parameters    :
--Date          :2011/10/19
--Authors       :TB
--MODS          :
--2004.5.7      :17/01/12 - Added Option to fetch ACTUALS or BUDGET
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

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

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

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

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

EXEC (@sql)
GO

/****** Object:  StoredProcedure [dbo].[sp_AC_Check_Cellphone]    Script Date: 10/02/2012 08:32:12 ******/
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: 10/02/2012 08:32:12 ******/
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))
    
    IF @intCountryID != -1    
      SELECT @strCountry_Code = Country_Dialing_Code
      FROM Slu_AW_Countries
      WHERE Slu_AW_Countries_ID = @intCountryID
    ELSE
    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

    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
        Set @strCellphone_Formated = @strCountry_Code + Right(@strCellphone,9)
      END          
    END
    
    SELECT @strCellphone_Formated
    
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[sp_AC_Filter_Prospect_Update_Export]    Script Date: 10/02/2012 08:34:01 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Filter_Prospect_Update_Export]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Filter_Prospect_Update_Export]
GO

/****** Object:  StoredProcedure [dbo].[sp_AC_Filter_Prospect_Update_Export]    Script Date: 10/02/2012 08:34:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

Create                           PROCEDURE [dbo].[sp_AC_Filter_Prospect_Update_Export]
	(
    	@CompanyID int,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@chkActiveOnly int = 1
   	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @sql varchar(8000)

	SET @Filter = ''
    SET @sql = ''

--> Type
	IF @TypeID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AC_Customer_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AC_Customer_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
--> Group
	IF @GroupID > 0 
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AC_Customer_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND ' + ' p.Lup_AC_Customer_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
		
--> Company
	IF @Filter = ''
		SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)
	ELSE
		SET @Filter = @Filter + ' AND ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)

--> Fetch only ACTIVE Products
    IF @chkActiveOnly = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Slu_AW_Active_ID = 1 '
            ELSE
                SET @Filter = @Filter + '  AND p.Slu_AW_Active_ID = 1 '
        END

    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.AC_Prospects_ID AS [ID], '
    SET @sql = @sql + ' p.Surname AS [Surname], '
    SET @sql = @sql + ' p.Firstnames AS [First Names], '
    SET @sql = @sql + ' p.Initials AS [Initials], '
    SET @sql = @sql + ' p.Slu_AW_Titles_ID AS [Title], '
    SET @sql = @sql + ' p.Contact_Name AS [Contact Name], '
    SET @sql = @sql + ' p.Slu_AW_Languages_ID AS [Language], '
    SET @sql = @sql + ' p.IDReg_Number AS [ID Reg No], '
    SET @sql = @sql + ' p.Customer_Number AS [Customer Number], '
    SET @sql = @sql + ' p.Old_Customer_Number AS [Old Customer Number], '
    SET @sql = @sql + ' p.Post_Box AS [Post Box], '
    SET @sql = @sql + ' p.Post_Office AS [Post Office], '
    SET @sql = @sql + ' p.Post_Code AS [Post Code], '
    SET @sql = @sql + ' p.Street_Address AS [Street Address], '
    SET @sql = @sql + ' p.Suburb AS [Suburb], '
    SET @sql = @sql + ' p.City AS [City], '
    SET @sql = @sql + ' p.Street_Post_Code AS [Street Post Code], '
    SET @sql = @sql + ' p.Delivery_Address AS [Delivery Address], '
    SET @sql = @sql + ' p.Delivery_Suburb AS [Delivery Suburb], '
    SET @sql = @sql + ' p.Delivery_City AS [Delivery City], '
    SET @sql = @sql + ' p.Delivery_Post_Code AS [Delivery Post Code], '
    SET @sql = @sql + ' p.Head_Office AS [Head Office], '
    SET @sql = @sql + ' p.Lup_AC_Customer_Types_ID AS [Customer Type], '
    SET @sql = @sql + ' p.Lup_AC_Customer_Groups_ID AS [Customer Group], '
    SET @sql = @sql + ' p.Slu_AW_Controllers_ID AS [Controller], '
    SET @sql = @sql + ' p.Lup_AS_Reps_ID AS [Sales Person], '
    SET @sql = @sql + ' p.Lup_AC_Sales_Areas_ID AS [Sales Area], '
    SET @sql = @sql + ' p.Slu_AW_Countries_ID AS [Country], '
    SET @sql = @sql + ' p.Cell_No AS [Cell Number], '
    SET @sql = @sql + ' p.Home_Tel_No AS [Home Number], '
    SET @sql = @sql + ' p.Work_Tel_No AS [Work Number], '
    SET @sql = @sql + ' p.Fax_No AS [Fax Number], '
    SET @sql = @sql + ' p.Web_Site_URL AS [Web Site], '
    SET @sql = @sql + ' p.Principal_Name AS [Principal Name], '
    SET @sql = @sql + ' p.Principal_Firstname AS [Principal Firstname], '
    SET @sql = @sql + ' p.Principal_Birthday AS [Principal Birthday], '
    SET @sql = @sql + ' p.Principal_Contact_Method_ID AS [Principal Contact Method], '
    SET @sql = @sql + ' p.Principal_Cell_No AS [Principal Cell Number], '
    SET @sql = @sql + ' p.Orders_URL AS [Accounts Email], '
    SET @sql = @sql + ' p.Home_Email AS [Home Email], '
    SET @sql = @sql + ' p.Work_Email AS [Work Email], '
    SET @sql = @sql + ' p.Start_Date AS [Start Date], '
    SET @sql = @sql + ' p.Tax_Number AS [Tax Number], '
    SET @sql = @sql + ' p.Sys_AW_Delivery_Methods_ID AS [Delivery Method], '
    SET @sql = @sql + ' p.Slu_AW_Active_ID AS [Active] '
    SET @sql = @sql + ' FROM AC_Prospects p '
    SET @sql = @sql + @Filter
    
            SET @sql = @sql + ' ORDER BY p.[Surname] '  

	EXEC (@sql)
--Select @sql

SET NOCOUNT OFF	
GO

/****** Object:  StoredProcedure [dbo].[sp_AC_Insert_CBilling_Temp]    Script Date: 10/02/2012 08:35:31 ******/
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Insert_CBilling_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Insert_CBilling_Temp]
GO
/****** Object:  StoredProcedure [dbo].[sp_AC_Insert_CBilling_Temp]    Script Date: 10/02/2012 08:35:31 ******/
SET ANSI_NULLS ON
GO

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

SET NOCOUNT ON

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

    SET @RetCode = 0
    SET @No_Days = 3

    SELECT TOP 1 @No_Days = ISNULL(Control_Value, 3)
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCBillingDays'
          
    Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
    
    Select @StartDayEndDate

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

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

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

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


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


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


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

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

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

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

-- Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
    SET @sql = @sql + 'ORDER BY t.AS_Transactions_ID '

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

        RETURN @RetCode
    END

EXEC (@sql)

SET @RetCode = 2

RETURN @RetCode
GO

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

/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Prospect_Update_Prospects]    Script Date: 10/01/2012 09:16:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!
-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Prospect_Update_Prospects
--Purpose       :Select Prospects for Prospect Updates
--Date          :2012-10-01
--Authors       :RGL
--MODS          :
-------------------------------------------------------------------------------
CREATE                  PROCEDURE [dbo].[sp_AP_Select_Prospect_Update_Prospects]
    (
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Surname AS [Surname], '
    SET @sql = @sql + ' p.Firstnames AS [First Names], '
    SET @sql = @sql + ' p.Initials AS [Initials], '
    SET @sql = @sql + ' p.Slu_AW_Titles_ID AS [Title], '
    SET @sql = @sql + ' p.Contact_Name AS [Contact Name], '
    SET @sql = @sql + ' p.Slu_AW_Languages_ID AS [Language], '
    SET @sql = @sql + ' p.IDReg_Number AS [ID Reg No], '
    SET @sql = @sql + ' p.Customer_Number AS [Customer Number], '
    SET @sql = @sql + ' p.Old_Customer_Number AS [Old Customer Number], '
    SET @sql = @sql + ' p.Post_Box AS [Post Box], '
    SET @sql = @sql + ' p.Post_Office AS [Post Office], '
    SET @sql = @sql + ' p.Post_Code AS [Post Code], '
    SET @sql = @sql + ' p.Street_Address AS [Street Address], '
    SET @sql = @sql + ' p.Suburb AS [Suburb], '
    SET @sql = @sql + ' p.City AS [City], '
    SET @sql = @sql + ' p.Street_Post_Code AS [Street Post Code], '
    SET @sql = @sql + ' p.Delivery_Address AS [Delivery Address], '
    SET @sql = @sql + ' p.Delivery_Suburb AS [Delivery Suburb], '
    SET @sql = @sql + ' p.Delivery_City AS [Delivery City], '
    SET @sql = @sql + ' p.Delivery_Post_Code AS [Delivery Post Code], '
    SET @sql = @sql + ' p.Head_Office AS [Head Office], '
    SET @sql = @sql + ' p.Lup_AC_Customer_Types_ID AS [Customer Type], '
    SET @sql = @sql + ' p.Lup_AC_Customer_Groups_ID AS [Customer Group], '
    SET @sql = @sql + ' p.Slu_AW_Controllers_ID AS [Controller], '
    SET @sql = @sql + ' p.Lup_AS_Reps_ID AS [Sales Person], '
    SET @sql = @sql + ' p.Lup_AC_Sales_Areas_ID AS [Sales Area], '
    SET @sql = @sql + ' p.Slu_AW_Countries_ID AS [Country], '
    SET @sql = @sql + ' p.Cell_No AS [Cell Number], '
    SET @sql = @sql + ' p.Home_Tel_No AS [Home Number], '
    SET @sql = @sql + ' p.Work_Tel_No AS [Work Number], '
    SET @sql = @sql + ' p.Fax_No AS [Fax Number], '
    SET @sql = @sql + ' p.Web_Site_URL AS [Web Site], '
    SET @sql = @sql + ' p.Principal_Name AS [Principal Name], '
    SET @sql = @sql + ' p.Principal_Firstname AS [Principal Firstname], '
    SET @sql = @sql + ' p.Principal_Birthday AS [Principal Birthday], '
    SET @sql = @sql + ' p.Principal_Contact_Method_ID AS [Principal Contact Method], '
    SET @sql = @sql + ' p.Principal_Cell_No AS [Principal Cell Number], '
    SET @sql = @sql + ' p.Orders_URL AS [Accounts Email], '
    SET @sql = @sql + ' p.Home_Email AS [Home Email], '
    SET @sql = @sql + ' p.Work_Email AS [Work Email], '
    SET @sql = @sql + ' p.Start_Date AS [Start Date], '
    SET @sql = @sql + ' p.Tax_NumberAS [Tax Number], '
    SET @sql = @sql + ' p.Sys_AW_Delivery_Methods_ID AS [Delivery Method], '
    SET @sql = @sql + ' p.Slu_AW_Active_ID AS [Active] '
    SET @sql = @sql + ' FROM  AC_Prospects'
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + '   AND Date_Captured > ' + '''' + CONVERT(varchar(30), DATEADD(year, 1, getdate())) + ''''
    SET @sql = @sql + ' ORDER BY [Surname] '

SET NOCOUNT OFF

EXEC (@sql)

GO

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

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

    --> NB NB: Customer ADD in POS saves with STREET address copied to 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], '

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

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

	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], ' If setup in sys_aw_options
    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], '

    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '

    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


IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Lookup_Editor_Data_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Lookup_Editor_Data_Select]
GO
/****** Object:  StoredProcedure [dbo].[sp_AW_Lookup_Editor_Data_Select]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AW_Lookup_Editor_Data_Select
--Purpose       :Selects Lookup table data for Lookup Editor
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Mods          :18/06/02 - Added Slu_AB_Account_Categories definition fields
--              :11/07/02 - Added Sys_AW_Tax_Codes
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table and its new columns
--              :09/07/03 - Added Sys_AW_Payment_Methods table (Autowiel !!)
--              :08/01/04 - Added System Lookups for Credit Manager
--              :29/02/04 - Added Lup_AS_CBilling_Types
--              :29/02/04 - Added Lup_AP_Fail_Reasons
--              :01/03/04 - Removed Date_Captured & User_ID from Inflections
--              :04/03/04 - Added Server, User and Password to Lup_AS_CBilling_Types
--              :09/03/04 - Added Lup_AP_Claim_Codes
--              :15/07/04 - Added Lup_AC_Customer_Groups
--2004.2.4      :31/05/05 - Added Terms_Value AS [Terms Days] in Slu_AW_Credit_Terms
--2004.2.7      :19/03/06 - Added Slu_AW_SMS_Messages
--2004.2.10     :19/03/06 - Added ORDER BY in @Choice = 'Sys_AB_Account_Categories'
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories
--2004.3.7      :23/07/07 - Added Lup_AC_Markup_Categories and Lup_AP_Markup_Groups
--              :23/09/07 - Added Lup_AB_Account_Groups
--              :28/09/07 - Added Lup_AB_Account_Divisions
--2004.3.8      :24/01/08 - Added Lup_AO_Supplier_Groups and Lup_AO_Supplier_Types
--              :04/05/08 - Added ORDER BY [Description] to most Lookups
--              :10/05/08 - Removed Min GP% field from Lup_AP_Product_Departments
--2004.3.9      :22/06/08 - Added Slu_AW_Shipping_Rates
--2004.4.0      :09/07/08 - Added Slu_AS_Volume_Discounts
--2004.4.1      :08/09/08 - Added Sys_AB_B2, Sys_AB_B3, Sys_AB_I3, Sys_AB_I4
--2004.4.3      :08/03/09 - Re-Indented ALL Lookups
--              :17/03/09 - Added Slu_AC_Statement_Messages
--2004.4.5      :29/05/09 - Added AW_Messages for Credit Manager Messages
--              :16/06/09 - Added Lup_AS_Procurement_Providers for Procurement Providers
--2004.4.8      :19/02/10 - Added Lup_AB_Transaction_Type_Maps for Bank Transaction Types Mapping
--2004.4.9      :07/09/10 - Added Lup_AP_Shipping_Agents for Shipping Agents
--2004.5.1      :18/05/11 - Added Lup_AF_Instructions for Factory Casing Tracking system
--2004.5.7-RGL  :2012-09-17 - Added Country_Dialing_Code column to Slu_AW_Countries
--2004.5.7-RGL  :2012-09-17 - Added Slu_AW_Countries_Mobile
------------------------------------------------------------------------------
CREATE                                                PROCEDURE [dbo].[sp_AW_Lookup_Editor_Data_Select]
	(
		@Choice varchar(50),
		@CompanyID int
	)
AS
    IF @Choice = 'Sys_AB_Account_Categories'
    	SELECT Sys_AB_Account_Categories_ID as [ID],
               Description as [Description],
               Sys_AB_B1_ID as [BS1],
               Sys_AB_B2_ID as [BS2],
               Sys_AB_B3_ID as [BS3],
               Sys_AB_I1_ID as [IS1],
               Sys_AB_I2_ID as [IS2],
               Sys_AB_I3_ID as [IS3],
               Sys_AB_I4_ID as [IS4],
               Sys_AB_Account_Types_ID as [Type],
               Notes
    	FROM Sys_AB_Account_Categories
        ORDER BY Sys_AB_B1_ID,
                 Sys_AB_B2_ID,
                 Sys_AB_B3_ID,
                 Sys_AB_I1_ID,
                 Sys_AB_I2_ID,
                 Sys_AB_I3_ID,
                 Sys_AB_I4_ID
    ELSE
    IF @Choice = 'Slu_AW_Active'
    	SELECT Slu_AW_Active_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User] 
    	FROM Slu_AW_Active
    ELSE
    IF @Choice = 'Lup_AC_Asset_Types'
    	SELECT Lup_AC_Asset_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Asset_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Banks'
    	SELECT Slu_AW_Banks_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Banks
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Branch_Codes'
    	SELECT Lup_AW_Branch_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Branch_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AS_Card_Institutions'
    	SELECT Slu_AS_Card_Institutions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Cashiers'
    	SELECT Lup_AS_Cashiers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Cashiers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Commission_Categories'
    	SELECT Lup_AS_Commission_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Commission_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Commission_Groups'
    	SELECT Lup_AP_Commission_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Commission_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Cost_Centers'
    	SELECT Lup_AB_Cost_Centers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Cost_Centers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Countries'
    	SELECT Slu_AW_Countries_ID as [ID],
               Description as [Description],
               Country_Code2 as [Country Code2],
               Country_Code3 as [Country Code3],
               Country_Number as [Country Number],
               Country_Dialing_Code as [Country Dialing Code],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Countries
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Credit_Terms'
    	SELECT Slu_AW_Credit_Terms_ID as [ID],
               Description as [Description],
               Terms_Value AS [Terms Days],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Credit_Terms
    ELSE
    IF @Choice = 'Slu_AW_Currencies'
    	SELECT Slu_AW_Currencies_ID as [ID],
               Description as [Description],
               Exchange_Rate as [Exchange Rate],
               Rate_Date as [Rate Date],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Currencies
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Types'
    	SELECT Lup_AC_Customer_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Discount_Categories'
    	SELECT Lup_AC_Discount_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Discount_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Discount_Groups'
    	SELECT Lup_AP_Discount_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Discount_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Inflections'
    	SELECT Slu_AW_Inflections_ID as [ID],
               Alternate1 as [Alternate1],
               Alternate2 as [Alternate2],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Inflections
        ORDER BY [Alternate1]
    ELSE
    IF @Choice = 'Slu_AW_Languages'
    	SELECT Slu_AW_Languages_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Mass_Codes'
    	SELECT Lup_AP_Mass_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Mass_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Months'
    	SELECT Slu_AW_Months_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Months
    ELSE
    IF @Choice = 'Lup_AP_PLU_Tabs'
    	SELECT Lup_AP_PLU_Tabs_ID as [ID],
               Tab_No as [Tab No],Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_PLU_Tabs
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
   ELSE 
   IF @Choice = 'Lup_AP_Product_Departments'
    	SELECT Lup_AP_Product_Departments_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Departments
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Groups'
    	SELECT Lup_AP_Product_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Locations'
    	SELECT Lup_AP_Product_Locations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Locations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Purchase_Categories'
    	SELECT Lup_AP_Purchase_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Purchase_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Manufacturers'
    	SELECT Lup_AP_Product_Manufacturers_ID as [ID],
               Description as [Description],
               Old_Code as [Old Code],
               Default_Supplier_ID as [Default Supplier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Manufacturers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Types'
    	SELECT Lup_AP_Product_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Provinces'
    	SELECT Slu_AW_Provinces_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Provinces
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Purchase_Price_Types'
    	SELECT Lup_AO_Purchase_Price_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Purchase_Price_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Reps'
    	SELECT Lup_AS_Reps_ID as [ID],
               Description as [Description],
               Lup_AS_Commission_Categories_ID as [Commission Category],
        	   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Reps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Rounding_Codes'
    	SELECT Lup_AP_Rounding_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Rounding_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Sales_Areas'
    	SELECT Lup_AC_Sales_Areas_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Sales_Areas
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AP_Sell_By_Codes'
    	SELECT Lup_AP_Sell_By_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Sell_By_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Stores'
    	SELECT Lup_AW_Stores_ID as [ID],
               Description as [Description],
               Slu_AW_Countries_ID as [Country],
               Slu_AW_Provinces_ID as [Province],
               City as [City],Suburb as [Suburb],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Stores
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Switch2_Types'
    	SELECT Lup_AP_Switch2_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Switch2_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Tills'
    	SELECT Lup_AS_Tills_ID as [ID],
               Description as [Description],
               Till_Float as [Till Float],
               Cashier_ID as [Cashier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Tills
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Titles'
    	SELECT Slu_AW_Titles_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Transaction_Profiles'
    	SELECT Lup_AS_Transaction_Profiles_ID as [ID],
               KeyCode as [KeyCode],
               Description as [Description],
               Sequence as [Sequence],
               Activated as [Activated],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Transaction_Profiles
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AP_Units_Of_Measure'
    	SELECT Slu_AP_Units_Of_Measure_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AP_Units_Of_Measure
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Workstations'
    	SELECT Lup_AW_Workstations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Workstations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Years'
    	SELECT Slu_AW_Years_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Years
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_YesNo'
    	SELECT Slu_AW_YesNo_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_YesNo
    ELSE
    IF @Choice = 'Sys_AW_Tax_Codes'
    	SELECT Sys_AW_Tax_Codes_ID as [ID],
               Description as [Description],
               Tax_Code as [Tax Code],
               Tax_Rate as [Tax Rate]
    	FROM Sys_AW_Tax_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Sys_AW_Payment_Methods'
    	SELECT Sys_AW_Payment_Methods_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Sys_AW_Payment_Methods
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Adverse_Reasons'
    	SELECT Slu_AC_Adverse_Reasons_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Adverse_Reasons
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Association_Types'
    	SELECT Slu_AC_Association_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Association_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Auditor_Rankings'
    	SELECT Slu_AC_Auditor_Rankings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Auditor_Rankings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bank_Codes'
    	SELECT Slu_AC_Bank_Codes_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Bank_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bond_Types'
    	SELECT Slu_AC_Bond_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Bond_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Business_Types'
    	SELECT Slu_AC_Business_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Business_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_ITC_Scores'
    	SELECT Slu_AC_ITC_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_ITC_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_KI_Scores'
    	SELECT Slu_AC_KI_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_KI_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Principal_Types'
    	SELECT Slu_AC_Principal_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Principal_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Profession_Types'
    	SELECT Slu_AC_Profession_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Profession_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Ratings'
    	SELECT Slu_AC_Ratings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Ratings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Security_Types'
    	SELECT Slu_AC_Security_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Security_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Shareholding_Types'
    	SELECT Slu_AC_Shareholding_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Shareholding_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Courts'
    	SELECT Slu_AW_Courts_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Courts
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Industry_Categories'
    	SELECT Slu_AW_Industry_Categories_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Industry_Categories
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Info_Report_Types'
    	SELECT Slu_AW_Info_Report_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Info_Report_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Lawsuit_Types'
    	SELECT Slu_AW_Lawsuit_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Lawsuit_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Nature_Of_Action'
    	SELECT Slu_AW_Nature_Of_Action_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Nature_Of_Action
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_CBilling_Providers'
    	SELECT Lup_AS_CBilling_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_CBilling_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Fail_Reasons'
    	SELECT Lup_AP_Fail_Reasons_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Fail_Reasons
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Claim_Codes'
    	SELECT Lup_AP_Claim_Codes_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Claim_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Groups'
    	SELECT Lup_AC_Customer_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               [User_ID] as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_SMS_Messages'
    	SELECT Slu_AW_SMS_Messages_ID as [ID],
               English as [English],
               Afrikaans as [Afrikaans],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_SMS_Messages
        ORDER BY [English]
    ELSE
    IF @Choice = 'Lup_AC_Markup_Categories'
    	SELECT Lup_AC_Markup_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Markup_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Markup_Groups'
    	SELECT Lup_AP_Markup_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Markup_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Groups'
    	SELECT Lup_AB_Account_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Divisions'
    	SELECT Lup_AB_Account_Divisions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Divisions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Groups'
    	SELECT Lup_AO_Supplier_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Types'
    	SELECT Lup_AO_Supplier_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Shipping_Rates'
        SELECT Slu_AW_Shipping_Rates_ID as [ID],
                Post_Code as [Post Code],
                Description as [Description],
                Location as [Locality],
                Rate_Per_Kg as [Rate/Kg],
                Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Shipping_Rates
        ORDER BY [Post Code], [Description]
    ELSE
    IF @Choice = 'Slu_AS_Volume_Discounts'
    	SELECT Slu_AS_Volume_Discounts_ID as [ID],
               Description as [Description],
               Sales_Qty as [Sales Qty],
               Discount_Perc as [Discount %],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Volume_Discounts
    ELSE
    IF @Choice = 'Sys_AB_B2'
    	SELECT Sys_AB_B2_ID as [BS2],
               Description as [Description]
    	FROM Sys_AB_B2
    ELSE
    IF @Choice = 'Sys_AB_B3'
    	SELECT Sys_AB_B3_ID as [BS3],
               Description as [Description]
    	FROM Sys_AB_B3
    ELSE
    IF @Choice = 'Sys_AB_I3'
    	SELECT Sys_AB_I3_ID as [IS3],
               Description as [Description]
    	FROM Sys_AB_I3
    ELSE
    IF @Choice = 'Sys_AB_I4'
    	SELECT Sys_AB_I4_ID as [IS4],
               Description as [Description]
    	FROM Sys_AB_I4
    ELSE
    IF @Choice = 'Slu_AC_Statement_Messages'
    	SELECT Slu_AC_Statement_Messages_ID as [ID],
               Description as [Description],
               Message as [Message],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Statement_Messages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'AW_Messages'
    	SELECT AW_Messages_ID as [ID],
               Description as [Description]
    	FROM AW_Messages
        ORDER BY [ID]
    ELSE
    IF @Choice = 'Lup_AS_Procurement_Providers'
    	SELECT Lup_AS_Procurement_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Procurement_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Transaction_Type_Maps'
    	SELECT Lup_AB_Transaction_Type_Maps_ID as [ID],
               Slu_AW_Banks_ID as [Bank],
               Sys_AB_Transaction_Types_ID as [Transaction Type],
               Mapping_CSV as [Mapping CSV List],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Transaction_Type_Maps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Bank], [Mapping CSV List]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agents'
    	SELECT Lup_AP_Shipping_Agents_ID as [ID],
               Description as [Description],
               Customer_Code as [Customer Code],
               Warehouse_No as [Warehouse No],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agents
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agent_Files'
    	SELECT Lup_AP_Shipping_Agent_Files_ID as [ID],
               Lup_AP_Shipping_Agents_ID as [Shipping Agent],
               Description as [Description],
               Server_Name as [Server Name],
               Login_Name as [Login Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agent_Files
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AF_Instructions'
    	SELECT Lup_AF_Instructions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AF_Instructions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    IF @Choice = 'Slu_AW_Countries_Mobile'
    	SELECT Slu_AW_Countries_Mobile_ID as [ID],
               Slu_AW_Countries_ID as [Country],
               Description as [Description],
               Mobile_Dialing_Code as [Mobile Code],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Slu_AW_Countries_Mobile
        ORDER BY [Description]
GO


---------------------------------------------------------------------------------
-- Begin Levy Implementation
---------------------------------------------------------------------------------

--N1 - Create new tables and columns

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

CREATE TABLE [dbo].[Lup_AP_AW_Weight](
	[Lup_AP_AW_Weight_ID] [smallint] IDENTITY(1,1) NOT NULL,
	[Description] [varchar](50) NULL,
	[Date_Captured] [datetime] NULL,	
	[User_ID] [int] NULL,
	[AW_User_Companies_ID] [int] NOT NULL,
	[Touched] [timestamp] NULL,
	[Slu_AW_Active_ID] [tinyint] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Lup_AP_AW_Weight] WITH NOCHECK ADD 
	CONSTRAINT [PK_Lup_AP_AW_Weight] PRIMARY KEY  CLUSTERED 
	(
		[Lup_AP_AW_Weight_ID]
	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
GO
setuser
GO

 CREATE  INDEX [IX_Lup_AP_AW_Weight_ID] ON [dbo].[Lup_AP_AW_Weight]([Lup_AP_AW_Weight_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
GO
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Lup_AP_AW_Weight].[Date_Captured]'
  -------------------------------------------------------
GO
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Lup_AP_AW_Weight].[User_ID]'
  -------------------------------------------------------
GO
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Lup_AP_AW_Weight].[AW_User_Companies_ID]'
  -------------------------------------------------------
GO
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Active]', N'[Lup_AP_AW_Weight].[Slu_AW_Active_ID]'
  -------------------------------------------------------
GO 
setuser
GO

IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AP_AW_Weight
  WHERE Lup_AP_AW_Weight_ID = 1
)
BEGIN
  INSERT INTO Lup_AP_AW_Weight
  (
    Description,
    Date_Captured
  )
  VALUES
  (
    '<None>',
    GetDate()
  )
END
Go
IF NOT EXISTS
(
  SELECT 1
  FROM Lup_AP_AW_Weight
  WHERE Description = 'Kilogram'
)
BEGIN
  INSERT INTO Lup_AP_AW_Weight
  (
    Description,
    Date_Captured 
  )
  VALUES
  (
    'Kilogram',
    GetDate()
  )
END
Go
IF NOT EXISTS
(
  SELECT Sys_AW_Lookup_Editor_ID
  FROM Sys_AW_Lookup_Editor
  WHERE TableName = 'Lup_AP_AW_Weight' And
        Caption = 'Unit Weight'
)
BEGIN

  Declare @Sys_AW_Lookup_Editor_ID Int

  Set @Sys_AW_Lookup_Editor_ID = 0

  Select @Sys_AW_Lookup_Editor_ID = MAX(Sys_AW_Lookup_Editor_ID)
  From Sys_AW_Lookup_Editor

  Set @Sys_AW_Lookup_Editor_ID = @Sys_AW_Lookup_Editor_ID + 1

  INSERT Sys_AW_Lookup_Editor
  (
    Sys_AW_Lookup_Editor_ID,
    TableName,
    Caption,
    ColumnWidths
  )
  VALUES
  (
    @Sys_AW_Lookup_Editor_ID,
    'Lup_AP_AW_Weight',
    'Unit Weight',
    '0,1005,0,0,1005'
   )
END
GO


--N4 Modify AP_Products

--1. Modify AP_Products 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='AP_Products' AND
        C.Name='Lup_AP_AW_Weight_ID'
) 
BEGIN
  ALTER TABLE AP_Products ADD Lup_AP_AW_Weight_ID Int NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Lup_AP_AW_Weight_ID]'
  -------------------------------------------------------
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='AP_Products' AND
        C.Name='Product_Weight'
) 
BEGIN
  ALTER TABLE AP_Products ADD Product_Weight Decimal(9,3) NULL
            
  -------------------------------------------------------
--  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_Weight_ID]'
  -------------------------------------------------------
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='AP_Products' AND
        C.Name='Slu_AW_YesNo_Levy_Item'
) 
BEGIN
  ALTER TABLE AP_Products ADD Slu_AW_YesNo_Levy_Item tinyint NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Slu_AW_YesNo_Levy_Item]'
  -------------------------------------------------------
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='AP_Products' AND
        C.Name='Levy_AP_Product_ID'
) 
BEGIN
  ALTER TABLE AP_Products ADD Levy_AP_Product_ID Int NULL
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products].[Levy_AP_Product_ID]'
  -------------------------------------------------------
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='AP_Products' AND
        C.Name='Levy_Weight_ID'
) 
BEGIN
  ALTER TABLE AP_Products ADD Levy_Weight_ID Int NULL

  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products].[Levy_Weight_ID]'
  -------------------------------------------------------
END
GO

UPDATE AP_Products
SET Slu_AW_YesNo_Levy_Item = 0
WHERE Slu_AW_YesNo_Levy_Item IS NULL
Go

UPDATE AP_Products
SET Lup_AP_AW_Weight_ID = 1
WHERE Lup_AP_AW_Weight_ID IS NULL 
GO


GO

--N2 - sp_AW_Lookup_Editor_Data_Select

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Lookup_Editor_Data_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Lookup_Editor_Data_Select]
GO
/****** Object:  StoredProcedure [dbo].[sp_AW_Lookup_Editor_Data_Select]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AW_Lookup_Editor_Data_Select
--Purpose       :Selects Lookup table data for Lookup Editor
--Parameters    :
--Date          :2002/06/18
--Authors       :TB
--Mods          :18/06/02 - Added Slu_AB_Account_Categories definition fields
--              :11/07/02 - Added Sys_AW_Tax_Codes
--              :05/12/02 - Replaced Slu_AB_Account_Categories with
--              :           Sys_AB_Account_Categories table and its new columns
--              :09/07/03 - Added Sys_AW_Payment_Methods table (Autowiel !!)
--              :08/01/04 - Added System Lookups for Credit Manager
--              :29/02/04 - Added Lup_AS_CBilling_Types
--              :29/02/04 - Added Lup_AP_Fail_Reasons
--              :01/03/04 - Removed Date_Captured & User_ID from Inflections
--              :04/03/04 - Added Server, User and Password to Lup_AS_CBilling_Types
--              :09/03/04 - Added Lup_AP_Claim_Codes
--              :15/07/04 - Added Lup_AC_Customer_Groups
--2004.2.4      :31/05/05 - Added Terms_Value AS [Terms Days] in Slu_AW_Credit_Terms
--2004.2.7      :19/03/06 - Added Slu_AW_SMS_Messages
--2004.2.10     :19/03/06 - Added ORDER BY in @Choice = 'Sys_AB_Account_Categories'
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories
--2004.3.7      :23/07/07 - Added Lup_AC_Markup_Categories and Lup_AP_Markup_Groups
--              :23/09/07 - Added Lup_AB_Account_Groups
--              :28/09/07 - Added Lup_AB_Account_Divisions
--2004.3.8      :24/01/08 - Added Lup_AO_Supplier_Groups and Lup_AO_Supplier_Types
--              :04/05/08 - Added ORDER BY [Description] to most Lookups
--              :10/05/08 - Removed Min GP% field from Lup_AP_Product_Departments
--2004.3.9      :22/06/08 - Added Slu_AW_Shipping_Rates
--2004.4.0      :09/07/08 - Added Slu_AS_Volume_Discounts
--2004.4.1      :08/09/08 - Added Sys_AB_B2, Sys_AB_B3, Sys_AB_I3, Sys_AB_I4
--2004.4.3      :08/03/09 - Re-Indented ALL Lookups
--              :17/03/09 - Added Slu_AC_Statement_Messages
--2004.4.5      :29/05/09 - Added AW_Messages for Credit Manager Messages
--              :16/06/09 - Added Lup_AS_Procurement_Providers for Procurement Providers
--2004.4.8      :19/02/10 - Added Lup_AB_Transaction_Type_Maps for Bank Transaction Types Mapping
--2004.4.9      :07/09/10 - Added Lup_AP_Shipping_Agents for Shipping Agents
--2004.5.1      :18/05/11 - Added Lup_AF_Instructions for Factory Casing Tracking system
--2004.5.7-RGL  :2012-09-17 - Added Country_Dialing_Code column to Slu_AW_Countries
--2004.5.7-RGL  :2012-09-17 - Added Slu_AW_Countries_Mobile
--2004.5.7-RGL  :2012-10-12 - Added Slu_AW_Weight
------------------------------------------------------------------------------
CREATE                                                PROCEDURE [dbo].[sp_AW_Lookup_Editor_Data_Select]
	(
		@Choice varchar(50),
		@CompanyID int
	)
AS
    IF @Choice = 'Sys_AB_Account_Categories'
    	SELECT Sys_AB_Account_Categories_ID as [ID],
               Description as [Description],
               Sys_AB_B1_ID as [BS1],
               Sys_AB_B2_ID as [BS2],
               Sys_AB_B3_ID as [BS3],
               Sys_AB_I1_ID as [IS1],
               Sys_AB_I2_ID as [IS2],
               Sys_AB_I3_ID as [IS3],
               Sys_AB_I4_ID as [IS4],
               Sys_AB_Account_Types_ID as [Type],
               Notes
    	FROM Sys_AB_Account_Categories
        ORDER BY Sys_AB_B1_ID,
                 Sys_AB_B2_ID,
                 Sys_AB_B3_ID,
                 Sys_AB_I1_ID,
                 Sys_AB_I2_ID,
                 Sys_AB_I3_ID,
                 Sys_AB_I4_ID
    ELSE
    IF @Choice = 'Slu_AW_Active'
    	SELECT Slu_AW_Active_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User] 
    	FROM Slu_AW_Active
    ELSE
    IF @Choice = 'Lup_AC_Asset_Types'
    	SELECT Lup_AC_Asset_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Asset_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Banks'
    	SELECT Slu_AW_Banks_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Banks
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Branch_Codes'
    	SELECT Lup_AW_Branch_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Branch_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AS_Card_Institutions'
    	SELECT Slu_AS_Card_Institutions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Card_Institutions
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Cashiers'
    	SELECT Lup_AS_Cashiers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Cashiers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Commission_Categories'
    	SELECT Lup_AS_Commission_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Commission_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Commission_Groups'
    	SELECT Lup_AP_Commission_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Commission_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Cost_Centers'
    	SELECT Lup_AB_Cost_Centers_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Cost_Centers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Countries'
    	SELECT Slu_AW_Countries_ID as [ID],
               Description as [Description],
               Country_Code2 as [Country Code2],
               Country_Code3 as [Country Code3],
               Country_Number as [Country Number],
               Country_Dialing_Code as [Country Dialing Code],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Countries
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Credit_Terms'
    	SELECT Slu_AW_Credit_Terms_ID as [ID],
               Description as [Description],
               Terms_Value AS [Terms Days],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Credit_Terms
    ELSE
    IF @Choice = 'Slu_AW_Currencies'
    	SELECT Slu_AW_Currencies_ID as [ID],
               Description as [Description],
               Exchange_Rate as [Exchange Rate],
               Rate_Date as [Rate Date],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Currencies
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Types'
    	SELECT Lup_AC_Customer_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Discount_Categories'
    	SELECT Lup_AC_Discount_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Discount_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Discount_Groups'
    	SELECT Lup_AP_Discount_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Discount_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Inflections'
    	SELECT Slu_AW_Inflections_ID as [ID],
               Alternate1 as [Alternate1],
               Alternate2 as [Alternate2],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Inflections
        ORDER BY [Alternate1]
    ELSE
    IF @Choice = 'Slu_AW_Languages'
    	SELECT Slu_AW_Languages_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
        FROM Slu_AW_Languages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Mass_Codes'
    	SELECT Lup_AP_Mass_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Mass_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Months'
    	SELECT Slu_AW_Months_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Months
    ELSE
    IF @Choice = 'Lup_AP_PLU_Tabs'
    	SELECT Lup_AP_PLU_Tabs_ID as [ID],
               Tab_No as [Tab No],Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_PLU_Tabs
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
   ELSE 
   IF @Choice = 'Lup_AP_Product_Departments'
    	SELECT Lup_AP_Product_Departments_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Departments
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Groups'
    	SELECT Lup_AP_Product_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Locations'
    	SELECT Lup_AP_Product_Locations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Locations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Purchase_Categories'
    	SELECT Lup_AP_Purchase_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Purchase_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Manufacturers'
    	SELECT Lup_AP_Product_Manufacturers_ID as [ID],
               Description as [Description],
               Old_Code as [Old Code],
               Default_Supplier_ID as [Default Supplier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Manufacturers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Product_Types'
    	SELECT Lup_AP_Product_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Product_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Provinces'
    	SELECT Slu_AW_Provinces_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Provinces
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Purchase_Price_Types'
    	SELECT Lup_AO_Purchase_Price_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Purchase_Price_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Reps'
    	SELECT Lup_AS_Reps_ID as [ID],
               Description as [Description],
               Lup_AS_Commission_Categories_ID as [Commission Category],
        	   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Reps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Rounding_Codes'
    	SELECT Lup_AP_Rounding_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Rounding_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Sales_Areas'
    	SELECT Lup_AC_Sales_Areas_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Sales_Areas
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AP_Sell_By_Codes'
    	SELECT Lup_AP_Sell_By_Codes_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Sell_By_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Stores'
    	SELECT Lup_AW_Stores_ID as [ID],
               Description as [Description],
               Slu_AW_Countries_ID as [Country],
               Slu_AW_Provinces_ID as [Province],
               City as [City],Suburb as [Suburb],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Stores
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Switch2_Types'
    	SELECT Lup_AP_Switch2_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Switch2_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Tills'
    	SELECT Lup_AS_Tills_ID as [ID],
               Description as [Description],
               Till_Float as [Till Float],
               Cashier_ID as [Cashier],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Tills
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Titles'
    	SELECT Slu_AW_Titles_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Titles
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_Transaction_Profiles'
    	SELECT Lup_AS_Transaction_Profiles_ID as [ID],
               KeyCode as [KeyCode],
               Description as [Description],
               Sequence as [Sequence],
               Activated as [Activated],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Transaction_Profiles
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AP_Units_Of_Measure'
    	SELECT Slu_AP_Units_Of_Measure_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AP_Units_Of_Measure
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AW_Workstations'
    	SELECT Lup_AW_Workstations_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AW_Workstations
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Years'
    	SELECT Slu_AW_Years_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Years
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_YesNo'
    	SELECT Slu_AW_YesNo_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_YesNo
    ELSE
    IF @Choice = 'Sys_AW_Tax_Codes'
    	SELECT Sys_AW_Tax_Codes_ID as [ID],
               Description as [Description],
               Tax_Code as [Tax Code],
               Tax_Rate as [Tax Rate]
    	FROM Sys_AW_Tax_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Sys_AW_Payment_Methods'
    	SELECT Sys_AW_Payment_Methods_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Sys_AW_Payment_Methods
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Adverse_Reasons'
    	SELECT Slu_AC_Adverse_Reasons_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Adverse_Reasons
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Association_Types'
    	SELECT Slu_AC_Association_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Association_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Auditor_Rankings'
    	SELECT Slu_AC_Auditor_Rankings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Auditor_Rankings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bank_Codes'
    	SELECT Slu_AC_Bank_Codes_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active]
    	FROM Slu_AC_Bank_Codes
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Bond_Types'
    	SELECT Slu_AC_Bond_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Bond_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Business_Types'
    	SELECT Slu_AC_Business_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Business_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_ITC_Scores'
    	SELECT Slu_AC_ITC_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_ITC_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_KI_Scores'
    	SELECT Slu_AC_KI_Scores_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_KI_Scores
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Principal_Types'
    	SELECT Slu_AC_Principal_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Principal_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Profession_Types'
    	SELECT Slu_AC_Profession_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Profession_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Ratings'
    	SELECT Slu_AC_Ratings_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Ratings
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Security_Types'
    	SELECT Slu_AC_Security_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Security_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AC_Shareholding_Types'
    	SELECT Slu_AC_Shareholding_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Shareholding_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Courts'
    	SELECT Slu_AW_Courts_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Courts
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Industry_Categories'
    	SELECT Slu_AW_Industry_Categories_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Industry_Categories
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Info_Report_Types'
    	SELECT Slu_AW_Info_Report_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Info_Report_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Lawsuit_Types'
    	SELECT Slu_AW_Lawsuit_Types_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Lawsuit_Types
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Nature_Of_Action'
    	SELECT Slu_AW_Nature_Of_Action_ID as [ID],
               Description as [Description],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Nature_Of_Action
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AS_CBilling_Providers'
    	SELECT Lup_AS_CBilling_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_CBilling_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Fail_Reasons'
    	SELECT Lup_AP_Fail_Reasons_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Fail_Reasons
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Claim_Codes'
    	SELECT Lup_AP_Claim_Codes_ID as [ID],
               Description as [Description],
               [Code] as [Code],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Claim_Codes
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AC_Customer_Groups'
    	SELECT Lup_AC_Customer_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               [User_ID] as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Customer_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_SMS_Messages'
    	SELECT Slu_AW_SMS_Messages_ID as [ID],
               English as [English],
               Afrikaans as [Afrikaans],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_SMS_Messages
        ORDER BY [English]
    ELSE
    IF @Choice = 'Lup_AC_Markup_Categories'
    	SELECT Lup_AC_Markup_Categories_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AC_Markup_Categories
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Markup_Groups'
    	SELECT Lup_AP_Markup_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Markup_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Groups'
    	SELECT Lup_AB_Account_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Account_Divisions'
    	SELECT Lup_AB_Account_Divisions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Account_Divisions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Groups'
    	SELECT Lup_AO_Supplier_Groups_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Groups
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AO_Supplier_Types'
    	SELECT Lup_AO_Supplier_Types_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AO_Supplier_Types
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Slu_AW_Shipping_Rates'
        SELECT Slu_AW_Shipping_Rates_ID as [ID],
                Post_Code as [Post Code],
                Description as [Description],
                Location as [Locality],
                Rate_Per_Kg as [Rate/Kg],
                Slu_AW_Active_ID as [Active] 
    	FROM Slu_AW_Shipping_Rates
        ORDER BY [Post Code], [Description]
    ELSE
    IF @Choice = 'Slu_AS_Volume_Discounts'
    	SELECT Slu_AS_Volume_Discounts_ID as [ID],
               Description as [Description],
               Sales_Qty as [Sales Qty],
               Discount_Perc as [Discount %],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AS_Volume_Discounts
    ELSE
    IF @Choice = 'Sys_AB_B2'
    	SELECT Sys_AB_B2_ID as [BS2],
               Description as [Description]
    	FROM Sys_AB_B2
    ELSE
    IF @Choice = 'Sys_AB_B3'
    	SELECT Sys_AB_B3_ID as [BS3],
               Description as [Description]
    	FROM Sys_AB_B3
    ELSE
    IF @Choice = 'Sys_AB_I3'
    	SELECT Sys_AB_I3_ID as [IS3],
               Description as [Description]
    	FROM Sys_AB_I3
    ELSE
    IF @Choice = 'Sys_AB_I4'
    	SELECT Sys_AB_I4_ID as [IS4],
               Description as [Description]
    	FROM Sys_AB_I4
    ELSE
    IF @Choice = 'Slu_AC_Statement_Messages'
    	SELECT Slu_AC_Statement_Messages_ID as [ID],
               Description as [Description],
               Message as [Message],
               Slu_AW_Active_ID as [Active] 
    	FROM Slu_AC_Statement_Messages
        ORDER BY [Description]
    ELSE
    IF @Choice = 'AW_Messages'
    	SELECT AW_Messages_ID as [ID],
               Description as [Description]
    	FROM AW_Messages
        ORDER BY [ID]
    ELSE
    IF @Choice = 'Lup_AS_Procurement_Providers'
    	SELECT Lup_AS_Procurement_Providers_ID as [ID],
               Description as [Description],
               Server_Name as [Server],
               Login_Name as [User Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AS_Procurement_Providers
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AB_Transaction_Type_Maps'
    	SELECT Lup_AB_Transaction_Type_Maps_ID as [ID],
               Slu_AW_Banks_ID as [Bank],
               Sys_AB_Transaction_Types_ID as [Transaction Type],
               Mapping_CSV as [Mapping CSV List],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AB_Transaction_Type_Maps
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Bank], [Mapping CSV List]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agents'
    	SELECT Lup_AP_Shipping_Agents_ID as [ID],
               Description as [Description],
               Customer_Code as [Customer Code],
               Warehouse_No as [Warehouse No],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agents
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE
    IF @Choice = 'Lup_AP_Shipping_Agent_Files'
    	SELECT Lup_AP_Shipping_Agent_Files_ID as [ID],
               Lup_AP_Shipping_Agents_ID as [Shipping Agent],
               Description as [Description],
               Server_Name as [Server Name],
               Login_Name as [Login Name],
               Login_Password as [Password],
               Folder as [Folder],
    		   Slu_AW_Active_ID as [Active] 
    	FROM Lup_AP_Shipping_Agent_Files
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE 
    IF @Choice = 'Lup_AF_Instructions'
    	SELECT Lup_AF_Instructions_ID as [ID],
               Description as [Description],
    		   Date_Captured as [Date Captured],
               User_ID as [User],
               AW_User_Companies_ID as [Company],
               Slu_AW_Active_ID as [Active] 
    	FROM Lup_AF_Instructions
    	WHERE AW_User_Companies_ID = @CompanyID
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Slu_AW_Countries_Mobile'
    	SELECT Slu_AW_Countries_Mobile_ID as [ID],
               Slu_AW_Countries_ID as [Country],
               Description as [Description],
               Mobile_Dialing_Code as [Mobile Code],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Slu_AW_Countries_Mobile
        ORDER BY [Description]
    ELSE    
    IF @Choice = 'Lup_AP_AW_Weight'
    	SELECT Lup_AP_AW_Weight_ID as [ID],
               Description as [Description],
               Date_Captured as [Date Captured],
               User_ID as [User],
               Slu_AW_Active_ID as [Active]
    	FROM Lup_AP_AW_Weight
        ORDER BY [Description]
        
GO

--N3 - sp_AP_Select_Products_Lups


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: 09/17/2012 14:49:06 ******/
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
-----------------------------------------------------------------------------

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 AP_Products_ID AS [ID],
    		[Description] As [Unit Weight] 
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY [Description]

SET NOCOUNT OFF
Go

--N5 sp_AP_Select_Product_Catalog

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Product_Catalog]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Product_Catalog]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Product_Catalog]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Catalog
--Purpose       :select's a specific Product's Catalog information 
--Functionality :
--Parameters    :
--Date          :2001/12/07
--Authors       :TB
--MODS          :26/05/03 - Added Slu_AW_YesNo_Non_Stock_Item AS [NonStockItem]
--              :14/02/04 - Added Max_Discount_Perc AS [MaxDiscPerc] and 
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--              :                 Slu_AW_YesNo_Max_Discount_Perc AS [UseMaxDiscPerc]
--2004.2.3      :12/05/05 - Added GL_Purchases_ID AS [GLPurchasesID]
--              :                 GL_Sales_ID AS [GLSalesID]
--              :           for simultaneous 'Stock' and 'Non-Stock' GRV posting
--              :19/05/05 - Added Standard_Cost AS [Standard Cost]
--2004.2.4      :23/10/05 - Added GL_COS_ID AS [GLCOSID] for GL Cost-of-Sales
--2004.3.4      :26/02/07 - Added Lup_AP_Purchase_Categories_ID AS [PurchaseCategory]
--2004.3.7      :25/07/07 - Added Lup_AP_Markup_Groups_ID AS [CostPlus Group]
--              :26/08/07 - Added Slu_AW_YesNo_Cost_Plus_Item AS [CostPlusItem]
--2004.4.6      :12/08/09 - Added Slu_AW_YesNo_Hide_Remote AS [HideRemote] - Commented
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_YesNo_Levy_Item As [IsLevy]
--2004.5.7 RGL  :2012-10-17 - Added Slu_AW_Weight_ID As [ProductWeight]        
--2004.5.7 RGL  :2012-10-17 - Added Levy_Product_ID AS [Levy_Product]
---------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Select_Product_Catalog]
    (
        @Product_ID int,
        @Company_ID int 
    )
AS

SET NOCOUNT ON

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

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

SET NOCOUNT OFF
Go

--N6 sp_AP_Levy_Product_Select

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Levy_Product_Select]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Levy_Product_Select]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Levy_Product_Select]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AP_Levy_Product_Select
--Purpose       :Selects Levy Product Info
--Parameters    :
--Date          :2012-10-19
--Authors       :RGL
------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Levy_Product_Select]
(
  @CompanyID Int,
  @AP_Products_ID int,
  @Description Varchar(50) OUTPUT,
  @Print_Description Varchar(30) OUTPUT,
  @Product_Code Varchar(20) OUTPUT,
  @Price1_Price1 money OUTPUT
)
AS

	SELECT         
	  @Description = Description,
	  @Print_Description = Print_Description,
	  @Product_Code = Product_Code,
	  @Price1_Price1 = Price1_Price1
	FROM
	  AP_Products
	WHERE
	  AP_Products_ID = @AP_Products_ID AND
	  Slu_AW_YesNo_Levy_Item = 1 AND
	  AW_User_Companies_ID = @CompanyID       
	  
GO

--N7 sp_AP_Levy_Product_Calc
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Levy_Product_Calc]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Levy_Product_Calc]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Levy_Product_Calc]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AP_Levy_Product_Calc
--Purpose       :Calculates Levy On Product
--Parameters    :
--Date          :2012-10-20
--Authors       :RGL
------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Levy_Product_Calc]
(
  @CompanyID int,
  @AP_Products_ID int,
  @Qty int,
  @AP_Levy_Products_ID int OUTPUT,
  @Description Varchar(50) OUTPUT,
  @Product_Code Varchar(20) OUTPUT,
  @Levy_Qty decimal(9,3) OUTPUT,
  @Price1_Price1 money OUTPUT,
  @TotalPrice1 money OUTPUT,
  @Tax money OUTPUT,
  @Tax_Rate decimal(5,3) OUTPUT
)
AS

  Declare @Sys_AW_Tax_Codes_ID Tinyint,
          @Levy_Weight_ID Int,
		  @Product_Weight Decimal(9,3),
		  @Product_Weight_ID Int,
		  @Hold_Price1_Price1 money
        
  SELECT @AP_Levy_Products_ID = Levy_AP_Product_ID,
		 @Product_Weight_ID = ISNULL(Lup_AP_AW_Weight_ID,1),
		 @Product_Weight = Product_Weight		 
  FROM AP_Products
  WHERE AP_Products_ID = @AP_Products_ID AND
        AW_User_Companies_ID = @CompanyID 

  SELECT @Description = Description,
         @Product_Code = Product_Code,
         @Hold_Price1_Price1 = Price1_Price1,
         @Levy_Weight_ID = ISNULL(Levy_Weight_ID,1),
         @Sys_AW_Tax_Codes_ID = Sys_AW_Tax_Codes_ID
  FROM AP_Products
  WHERE AP_Products_ID = @AP_Levy_Products_ID AND
        AW_User_Companies_ID = @CompanyID

  SELECT @Tax_Rate = Tax_Rate 
  FROM Sys_AW_Tax_Codes
  WHERE Sys_AW_Tax_Codes_ID = @Sys_AW_Tax_Codes_ID
  

  SET @Levy_Qty = 1
  SET @TotalPrice1 = 0
  SET @Tax = 0
  SET @Price1_Price1 = 0
  
  IF @Product_Weight_ID = @Levy_Weight_ID
  BEGIN
    IF @Levy_Weight_ID = 1
    BEGIN
    
      SET @Price1_Price1 = @Hold_Price1_Price1
      SET @Levy_Qty = @Qty
      SELECT @TotalPrice1 = @Price1_Price1 * @Levy_Qty
    
      SET @Tax = (@TotalPrice1 / 100) * @Tax_Rate
      SET @Tax = Round(@Tax,2)
      SET @TotalPrice1 = Round(@TotalPrice1,2)
    
    END
    ELSE
    IF ISNULL(@Product_Weight,0) <> 0.00
    BEGIN   
        
      SET @Price1_Price1 = @Hold_Price1_Price1  
      SET @Levy_Qty = @Qty * @Product_Weight
      SELECT @TotalPrice1 = @Price1_Price1 * @Levy_Qty
    
      SET @Tax = (@TotalPrice1 / 100) * @Tax_Rate
      SET @Tax = Round(@Tax,2)
      SET @TotalPrice1 = Round(@TotalPrice1,2)
    
    END
  END    
  
GO

--N8 sp_AP_Update_Product_Filters

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Product_Filters]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Product_Filters]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Update_Product_Filters]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Update_Product_Filters
--Purpose       :
--Date          :2005/04/27
--Authors       :TB
--MODS          :
--2004.3.4      :20/02/07 - Added Product Location field
--              :20/02/07 - Added Purchase Category field
--2004.3.5      :15/06/07 - Added @chkLinkOnly input parameter
--2004.5.7 RGL  :2012-10-20 - Added @Weight and @Levy_Product input parameter
-------------------------------------------------------------------------------

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

SET NOCOUNT ON

    DECLARE @ReturnValue int

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

RETURN @ReturnValue
Go

--N9 sp_AP_Filter_Product_Filters

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Product_Filters]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Product_Filters]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Filter_Product_Filters]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_Filters
--Purpose       :Filters Products to set Product Filters globally
--Joins         :Tables: AP_Products, AO_Suppliers,
--Date          :2005/04/27
--Authors       :TB
--MODS          :
--2004.3.4      :20/02/07 - Added Product Location field
--              :27/03/07 - Added Purchase Category AS [Purchase]
--2004.5.7 RGL  :2012-10-20 - Added Product Levy field
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Filter_Product_Filters]
	(
    	@CompanyID int,
    	@SupplierID int = -1,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
        @LocationID int = -1,
        @PurchaseID int = -1
	)
AS

SET NOCOUNT ON

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

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

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

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

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

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

        SET @SQL = @SQL + ' p.Default_Supplier_ID AS [Supplier], '
        SET @SQL = @SQL + ' p.Lup_AP_Product_Manufacturers_ID AS [Manufacturer], '
        SET @SQL = @SQL + ' p.Lup_AP_Product_Types_ID AS [Type], '
        SET @SQL = @SQL + ' p.Lup_AP_Product_Groups_ID AS [Group], '
        SET @SQL = @SQL + ' p.Lup_AP_Product_Departments_ID AS [Department], '
        SET @SQL = @SQL + ' p.Lup_AP_Product_Locations_ID AS [Location], '
        SET @SQL = @SQL + ' p.Lup_AP_Purchase_Categories_ID AS [Purchase], '
        SET @SQL = @SQL + ' p.Slu_AW_Active_ID AS [Active], '
        SET @SQL = @SQL + ' p.Levy_AP_Product_ID AS [Levy], '        
        SET @SQL = @SQL + ' p.Product_Weight AS [Weight] '

        SET @SQL = @SQL + ' FROM AP_Products p '
        SET @SQL = @SQL + '     INNER JOIN AO_Suppliers s '
        SET @SQL = @SQL + '         ON s.AO_Suppliers_ID = p.Default_Supplier_ID '
        SET @SQL = @SQL + @Filter
        SET @SQL = @SQL + ' ORDER BY p.[Description] '

		EXEC (@SQL)

	END
SET NOCOUNT OFF	
GO

--N10 sp_AP_Product_Filter_Lups
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: 09/17/2012 14:49:06 ******/
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
---------------------------------------------------------------------------------
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 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 [Description] ASC

SET NOCOUNT OFF
Go

--N11 sp_AO_Select_Order_Details_Product_Details_Levy

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AO_Select_Order_Details_Product_Details_Levy]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AO_Select_Order_Details_Product_Details_Levy]
GO
/****** Object:  StoredProcedure [dbo].[sp_AO_Select_Order_Details_Product_Details_Levy]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------
--Description   :sp_AO_Select_Order_Details_Product_Details_Levy
--Purpose       :Gets the LEVY details for a product 
--Functionality :
--Parameters    :
--Date          :2012-10-21
--Authors       :RGL
--MODS          :
-----------------------------------------------------------------------------
Create Procedure [dbo].[sp_AO_Select_Order_Details_Product_Details_Levy]
    (
        @AP_Products_ID int,
    	@Suppliers_ID int,
    	@Order_qty int,
    	@Company_ID int,
    	
    	@Levy_AP_Product_ID int OUTPUT,  	
		@Product varchar(30) OUTPUT,
		@Price1_Price1 money OUTPUT,
		@Price1_Price2 money OUTPUT,
		@GrossPurchasePrice money OUTPUT,
		@Lead_Time smallint OUTPUT,
		@Service_Level decimal(9,3) OUTPUT,
		@Last_Sale_Date datetime OUTPUT,
		@On_Hand decimal(9,3) OUTPUT,
		@Job_Reserved decimal(9,3) OUTPUT,
		@Last_Cost money OUTPUT,
		@Levy_Qty decimal(9,3) OUTPUT,
		@Orders_Pending  decimal(9,3) OUTPUT, 
		@Trade_Discount_Formula_ID int OUTPUT, 
		@Rebate_Discount_Formula_ID	int OUTPUT,
		@Tax_Codes_ID tinyint OUTPUT,
		@TotalPrice1 money OUTPUT, 
		@Tax money OUTPUT,
		@Tax_Rate decimal(5,3) OUTPUT
    )
AS

SET NOCOUNT ON

    DECLARE 
		@Use_Supplier_Discounts Bit,
    	@Use_Rebate_Disc_GL_Acc Bit,
    	@Use_Other_Disc_GL_Acc Bit,
    	@Rebate_Disc_GL_Acc int,
    	@Other_Disc_GL_Acc int,
    	--@Purchases_Contol_Acc_ID int,
    	@OtherDisc money,
    	@RebateDisc money,
    	@TradeDisc money,
    	@OtherDiff money,
    	@RebateDiff money,
    	@TradeDiff money,
    	
    	@Product_Weight_ID Int,
    	@Product_Weight Decimal(9,3),
    	@Levy_Weight_ID Int,
    	@Hold_Price1_Price1 money,
    	@Hold_Price1_Price2 money    	
    	
    
        SELECT @Levy_AP_Product_ID = Levy_AP_Product_ID,
			   @Product_Weight_ID = ISNULL(Lup_AP_AW_Weight_ID,1),
               @Product_Weight = Product_Weight
        FROM AP_Products 
		WHERE AP_Products_ID = @AP_Products_ID AND 
    		  AW_User_Companies_ID = @Company_ID 
    		    
    	SET @Use_Supplier_Discounts = 1
    	SET	@Use_Rebate_Disc_GL_Acc = 1
    	SET	@Use_Other_Disc_GL_Acc = 1
    	SET	@Rebate_Disc_GL_Acc = 1
    	SET	@Other_Disc_GL_Acc = 1
     		    
    	--SELECT @Purchases_Contol_Acc_ID = AB_Accounts_ID 
    	--FROM AB_Control_Accounts
    	--WHERE Control_Number = 301
    
    	SELECT @Last_Cost = ISNULL(Last_Cost,0),
    	       @Levy_Weight_ID = ISNULL(Levy_Weight_ID,1),
    	       @Hold_Price1_Price1 = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price1,Price2_Effective_Date, Price2_Price1,getdate()),
    	       @Hold_Price1_Price2 = dbo.GetEffectivePrice(Price1_Effective_Date, Price1_Price2,Price2_Effective_Date, Price2_Price2,getdate()),
	    		@Product = [Description],
    			@Lead_Time = (SELECT DISTINCT Lead_Time 
    							FROM AP_Products_Suppliers 
    							WHERE AP_Products_ID = @AP_Products_ID AND AO_Suppliers_ID = @Suppliers_ID),
    			@Service_Level = Service_Level,
    			@Last_Sale_Date = Last_Sale_Date,
	    		@On_Hand = On_Hand,
				@Job_Reserved = Job_Reserved + Sales_Order_Reserved,
    			@Last_Cost = Last_Cost,	
	   			@Orders_Pending = 0,  		
	            @Trade_Discount_Formula_ID = 1,    			
		        @Rebate_Discount_Formula_ID = 1,    			
			    @Tax_Codes_ID = (SELECT Sys_AW_Tax_Codes_ID FROM AO_Suppliers WHERE AO_Suppliers_ID = @Suppliers_ID)
    	FROM AP_Products 
    	WHERE AP_Products_ID = @Levy_AP_Product_ID AND 
    		  AW_User_Companies_ID = @Company_ID 
     
		SELECT @Tax_Rate = Tax_Rate 
		FROM Sys_AW_Tax_Codes
		WHERE Sys_AW_Tax_Codes_ID = @Tax_Codes_ID    
		 
    	SET @OtherDisc = 0
    	SET @RebateDisc = 0
    	SET @TradeDisc = 0
    			
    	SET @OtherDiff = 0
    	SET @RebateDiff = 0
    	SET @TradeDiff = 0
    
		SET @Levy_Qty = 1
		SET @GrossPurchasePrice = 0
		--SET @Tax = 0
		SET @Last_Cost = 0
		
		SET @Price1_Price1 = 0
		SET @Price1_Price1 = 0

	  IF @Product_Weight_ID = @Levy_Weight_ID
	  BEGIN
		IF @Levy_Weight_ID = 1
		BEGIN
	    
		  SET @Price1_Price1 = @Hold_Price1_Price1
		  SET @Price1_Price2 = @Hold_Price1_Price2
		  SET @Levy_Qty = @Order_qty
		  
		  SELECT @TotalPrice1 = @Price1_Price1 * @Levy_Qty
	    
		  SET @Tax = (@TotalPrice1 / 100) * @Tax_Rate
		  SET @Tax = Round(@Tax,2)
		  SET @TotalPrice1 = Round(@TotalPrice1,2)
	    
		END
		ELSE
		IF ISNULL(@Product_Weight,0) <> 0.00
		BEGIN   
	        
		  SET @Price1_Price1 = @Hold_Price1_Price1
		  SET @Price1_Price2 = @Hold_Price1_Price2  
		  SET @Levy_Qty = @Order_qty * @Product_Weight
		  
		  SELECT @TotalPrice1 = @Price1_Price1 * @Levy_Qty
	    
		  SET @Tax = (@TotalPrice1 / 100) * @Tax_Rate
		  SET @Tax = Round(@Tax,2)
		  SET @TotalPrice1 = Round(@TotalPrice1,2)
	    
		END
	  END       
    
    	SET @GrossPurchasePrice = @Price1_Price1 * @Order_qty    			      	

SET NOCOUNT OFF
Go

--N12 sp_AS_Day_End

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
/****** Object:  StoredProcedure [dbo].[sp_AS_Day_End]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Day_End
--Purpose       :Daily Sales Day-End procedure
--              :Inserts GL Journal and GL Transactions to GL CONTROL ACCOUNTS:
--              :1. DEBTORS, SALES, & VAT CONTROL
--              :2. RECEIPTS to DEBTORS & CASH CONTROL
--              :3. INTEREST JOURNALS to DEBTORS & INTEREST RECEIVED - Removed 31/05/04
--              :4. SETTLEMENT DISCOUNT to DEBTORS & SETTLEMENT DISCOUNT ALLOWED
--              :    for the following AS_Transaction_Types:
--              :        3=Invoice, 4=Refund, 7=Receipt,
--              :        15=Interest Journal, 18=Settlement Discount
--              :
--              :Ignores 5=Customer Journals. This is updated in Customer Journals
--              :-------------------------------------------------------
--              :GL Transaction Ref no's: !! REDUNDANT 15/10/03 !!
--              :Sales:            Debtors = 90, Sales = 91, VAT = 92
--              :Cost Of Sales:    Cost Of Sales = 82, Inventory = 83
--              :Receipts:         Debtors = 93, Cash = 94
--              :Interest:         Debtors = 95, Interest Received = 96 - Removed 31/05/04
--              :Settlement:       Debtors = 97, Discount Allowed = 98
--              :-------------------------------------------------------
--Date          :2002/02/06
--Authors       :TB
--MODS          :07/07/02 - Inserted VAT on Settlement Discount transaction
--              :07/07/02 - Changed Sys_AB_Transaction_Types_ID for each TranType
--              :19/07/02 - Added RECEIPTS TranTypes 21 (Back Office Receipt) and
--              :           22 (EFT Receipt) and split RECEIPTS updates to GL
--              :28/09/02 - Removed @Date parameter passed in from UI and replaced
--              :           it with @DayEndDate (SERVER date) to eliminate DE's
--              :           on different computers with varying Realtime Clock
--              :21/12/02 - Modified @GLControlAccount def from smallint to int
--              :04/09/03 - Added to Post Day-End COST OF SALES to Inventory/C.O.S.
--              :           if chkGRVtoInventoryCOS parameter is vbChecked
--              :15/10/03 - Replaced ALL GL Transaction Ref no's number and apply
--              :           @NextGLTranID reference number to ALL GL Transactions
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :31/05/04 - Removed Customer Interest updated here in Day-End.
--              :           Customer Interest update was removed and put back into 
--              :           sp_AC_Customer_Journals_Insert_Update on 28/07/02 !!
--2004.2.4      :04/06/05 - Added filter @CompanyID in ALL WHERE clauses !!!!!!
--              :05/06/05 - Added fetch PICKLIST from NEW AS_Day_Ends table
--              :05/06/05 - Added INSERT NEW AS_Day_Ends table
--2004.2.7      :28/03/06 - Replaced GL TranType 24 (Accounts Receivable - Settlement)
--              :           with GL TranType 22 (Accounts Receivable - Journal)
--              :           for Settlement Discount portion of Day-End procedure
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.6      :08/08/09 - Added UPDATE DAY-END FLAG in NEW AS_Till_Payouts table
--2004.5.3      :09/08/11 - Added Day-End CUTOFF DATE using Transaction_Date and DELETE DAY-END
--2004.5.5      :10/11/11 - Added Set @RetVal = 1 in DO DAY-END when Day-End completed succesfully
--2004.5.7 RGL  :2012-10-22 - Split Levy product transactions to Sales and COS GL 
--                            accounts as setup on Products
-------------------------------------------------------------------------------
---- 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 Customer_Cursor 
        				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

--N13 sp_AO_Insert_AO_Transactions

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
/****** Object:  StoredProcedure [dbo].[sp_AO_Insert_AO_Transactions]    Script Date: 09/17/2012 14:49:06 ******/
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
------------------------------------------------------------------------------
--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
						IF IsNull(@AO_GRV_ID,0) = 0
						BEGIN
						--> 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
						
						END
						ELSE
						BEGIN
                    
							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      
									Union
									SELECT 0,
										   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 = 0                                                                      
								)
	    
                    		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
                    	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

--N14 Create Levy Product and GL

IF NOT EXISTS
(
  SELECT 1
  FROM AP_Products
  WHERE Product_Code = 'RTW-Levy'
)
BEGIN
  Declare 
		@AO_Suppliers_ID	Int,
		@AP_Products_ID		Int 
  
  SET @AO_Suppliers_ID = 0
  SET @AP_Products_ID = 0
  
  SELECT TOP 1 @AO_Suppliers_ID = AO_Suppliers_ID
  FROM AO_Suppliers
  WHERE UPPER(Supplier_Name) IN ('NONE', '<NONE>', '< NONE >')
  
  IF @AO_Suppliers_ID = 0
  BEGIN 
	INSERT INTO 
			[AO_Suppliers]
           ([Supplier_Name]
           ,[Supplier_Number]
           ,[Old_Code]
           ,[Lup_AO_Purchase_Price_Types_ID]
           ,[Use_Supplier_Discount_Defaults]
           ,[AW_Trade_Discount_Formula_ID]
           ,[AW_Rebate_Discount_Formula_ID]
           ,[AB_Other_Discounts_Account_ID]
           ,[AB_Rebate_Discount_Account_ID]
           ,[Use_Other_Discount_Control_Acc]
           ,[Use_Rebate_Discount_Control_Acc]
           ,[Account_Balance]
           ,[Current_Balance]
           ,[Days_30]
           ,[Days_60]
           ,[Days_90]
           ,[Days_120]
           ,[Days_150]
           ,[Days_180]
           ,[Start_Date]
           ,[Credit_Limit]
           ,[Slu_AW_Credit_Terms_ID]
           ,[Default_Settlement_Discount]
           ,[Supplier_Contact]
           ,[Sys_AC_Account_Status_ID]
           ,[Sys_AW_Tax_Codes_ID]
           ,[Tax_Number]
           ,[Post_Box]
           ,[Post_Office]
           ,[Post_Code]
           ,[Street_Address]
           ,[Suburb]
           ,[City]
           ,[Street_Post_Code]
           ,[Slu_AW_Countries_ID]
           ,[Supplier_Telephone]
           ,[Contact_Cellphone]
           ,[Supplier_Fax]
           ,[Web_Site_URL]
           ,[Orders_URL]
           ,[Sys_AO_Delivery_Methods_ID]
           ,[Email_Address]
           ,[Notes]
           ,[Slu_AW_Banks_ID]
           ,[Bank_Branch]
           ,[Bank_Branch_Code]
           ,[Account_Name]
           ,[Account_Number]
           ,[Date_Captured]
           ,[User_ID]
           ,[AW_User_Companies_ID]
           ,[Slu_AW_Active_ID]
           ,[Lup_AO_Supplier_Types_ID]
           ,[Lup_AO_Supplier_Groups_ID]
           ,[Sys_AC_Account_Types_ID])
     VALUES
           ('<NONE>'--(<Supplier_Name, varchar(40),>
           ,NULL--<Supplier_Number, varchar(10),>
           ,NULL--<Old_Code, varchar(10),>
           ,1--<Lup_AO_Purchase_Price_Types_ID, tinyint,>
           ,1--<Use_Supplier_Discount_Defaults, bit,>
           ,1--<AW_Trade_Discount_Formula_ID, smallint,>
           ,1--<AW_Rebate_Discount_Formula_ID, smallint,>
           ,1--<AB_Other_Discounts_Account_ID, int,>
           ,1--<AB_Rebate_Discount_Account_ID, int,>
           ,0--<Use_Other_Discount_Control_Acc, bit,>
           ,0--<Use_Rebate_Discount_Control_Acc, bit,>
           ,0.00--<Account_Balance, money,>
           ,0.00--<Current_Balance, money,>
           ,0.00--<Days_30, money,>
           ,0.00--<Days_60, money,>
           ,0.00--<Days_90, money,>
           ,0.00--<Days_120, money,>
           ,0.00--<Days_150, money,>
           ,0.00--<Days_180, money,>
           ,'2012-10-01'--<Start_Date, datetime,>
           ,0.00--<Credit_Limit, money,>
           ,1--<Slu_AW_Credit_Terms_ID, tinyint,>
           ,0.00--<Default_Settlement_Discount, decimal(7,2),>
           ,NULL--<Supplier_Contact, varchar(30),>
           ,1--<Sys_AC_Account_Status_ID, tinyint,>
           ,1--<Sys_AW_Tax_Codes_ID, tinyint,>
           ,NULL--<Tax_Number, varchar(16),>
           ,NULL--<Post_Box, varchar(20),>
           ,NULL--<Post_Office, varchar(30),>
           ,NULL--<Post_Code, varchar(10),>
           ,NULL--<Street_Address, varchar(40),>
           ,NULL--<Suburb, varchar(30),>
           ,NULL--<City, varchar(30),>
           ,NULL--<Street_Post_Code, varchar(10),>
           ,193--<Slu_AW_Countries_ID, smallint,>
           ,NULL--<Supplier_Telephone, varchar(20),>
           ,NULL--<Contact_Cellphone, varchar(20),>
           ,NULL--<Supplier_Fax, varchar(20),>
           ,NULL--<Web_Site_URL, varchar(100),>
           ,NULL--<Orders_URL, varchar(100),>
           ,1--<Sys_AO_Delivery_Methods_ID, tinyint,>
           ,NULL--<Email_Address, varchar(40),>
           ,NULL--<Notes, varchar(500),>
           ,NULL--<Slu_AW_Banks_ID, smallint,>
           ,NULL--<Bank_Branch, varchar(40),>
           ,NULL--<Bank_Branch_Code, varchar(20),>
           ,NULL--<Account_Name, varchar(50),>
           ,NULL--<Account_Number, varchar(20),>
           ,GetDate()--<Date_Captured, datetime,>
           ,-1--<User_ID, int,>
           ,1--<AW_User_Companies_ID, int,>
           ,1--<Slu_AW_Active_ID, tinyint,>
           ,1--<Lup_AO_Supplier_Types_ID, smallint,>
           ,1--<Lup_AO_Supplier_Groups_ID, smallint,>
           ,2)--<Sys_AC_Account_Types_ID, tinyint,>)
    
	SELECT @AO_Suppliers_ID = SCOPE_IDENTITY()                      
	
  END           

  INSERT INTO AP_Products
  (
    [Description], 
    Print_Description, 
    Product_Code, 
    SKU_Code, 
    Pack_Size, 
    Measure, 
    Slu_AP_Units_Of_Measure_ID, 
    Manufacturer_Code, 
    Manufacturer_Description, 
    Slu_AW_YesNo_Self_Managed, 
    Lup_AP_Product_Manufacturers_ID, 
    Default_Supplier_ID, 
    Lup_AP_Product_Types_ID, 
    Lup_AP_Product_Groups_ID, 
    Lup_AP_Product_Departments_ID, 
    Lup_AP_Product_Locations_ID, 
    Lup_AP_Sell_By_Codes_ID, 
    Alternate_Code1, 
    Alternate_Code2, 
    Supercession, 
    Last_Cost, 
    Average_Cost, 
    Standard_Cost, 
    Standard_Disc1, 
    Standard_Disc2, 
    Average_Markup, 
    Price1_Effective_Date, 
    Price1_Price1, 
    Price1_Price2, 
    Price2_Effective_Date, 
    Price2_Price1, 
    Price2_Price2, 
    Lup_AP_Rounding_Codes_ID, 
    Sys_AW_Tax_Codes_ID, 
    Lup_AP_Discount_Groups_ID, 
    Lup_AP_Commission_Groups_ID, 
    Pack_Volume, 
    Lup_AP_Mass_Codes_ID, 
    Pack_Mass, 
    Strength, 
    On_Hand, 
    Sales_Order_Reserved, 
    Quote_Reserved, 
    Job_Reserved, 
    Min_Stock_Level, 
    Last_Sale_Date, 
    Service_Level, 
    Max_Order_Qty, 
    Min_Order_Qty, 
    Slu_AW_YesNo_Assembly, 
    Serial_Number, 
    Show_Image, 
    Image_File_Name, 
    Slu_AW_YesNo_Edit_Price, 
    Slu_AW_YesNo_Edit_Discount, 
    Max_Discount_Perc, 
    Slu_AW_YesNo_Max_Discount_Perc, 
    Memo, 
    Keywords, 
    PLU_Tab, 
    Slu_AW_YesNo_Non_Stock_Item, 
    GL_Purchases_ID, 
    GL_Sales_ID, 
    GL_COS_ID, 
    Date_Captured, 
    User_ID, 
    AW_User_Companies_ID, 
    Slu_AW_Active_ID, 
    Lup_AP_Purchase_Categories_ID, 
    Lup_AP_Markup_Groups_ID, 
    Slu_AW_YesNo_Cost_Plus_Item, 
    Lup_AP_AW_Weight_ID, 
    Product_Weight, 
    Slu_AW_YesNo_Levy_Item, 
    Levy_AP_Product_ID, 
    Levy_Weight_ID
  )
  VALUES
  (
    'Redisa Tyre Waste Levy', --[Description], 
    'Redisa Tyre Waste Levy', --Print_Description, 
    'RTW-Levy', --Product_Code, 
    NULL, --SKU_Code, 
    1.000, --Pack_Size, 
    0.000, --Measure, 
	1, --Slu_AP_Units_Of_Measure_ID, 
	NULL, --Manufacturer_Code, 
	NULL, --Manufacturer_Description, 
	0, --Slu_AW_YesNo_Self_Managed, 
	1, --Lup_AP_Product_Manufacturers_ID, 
	@AO_Suppliers_ID, --Default_Supplier_ID,
	1, --Lup_AP_Product_Types_ID, 
	1, --Lup_AP_Product_Groups_ID, 
	1, --Lup_AP_Product_Departments_ID, 
	1, --Lup_AP_Product_Locations_ID, 
	1, --Lup_AP_Sell_By_Codes_ID, 
	NULL, --Alternate_Code1, 
	NULL, --Alternate_Code2, 
	NULL, --Supercession, 
	2.30, --Last_Cost, 
	2.30, --Average_Cost, 
	0.00, --Standard_Cost, 
	0.00, --Standard_Disc1, 
	0.00, --Standard_Disc2, 
	0.0000, --Average_Markup, 
	'2012-10-01 00:00:00', --Price1_Effective_Date, 
	2.30, --Price1_Price1, 
	0.00, --Price1_Price2, 
	'2000-01-01 00:00:00', --Price2_Effective_Date, 
	0.00, --Price2_Price1, 
	0.00, --Price2_Price2, 
	1, --Lup_AP_Rounding_Codes_ID, 
	1, --Sys_AW_Tax_Codes_ID, 
	1, --Lup_AP_Discount_Groups_ID, 
	1, --Lup_AP_Commission_Groups_ID, 
	0.000, --Pack_Volume, 
	1, --Lup_AP_Mass_Codes_ID, 
	0.000, --Pack_Mass, 
	NULL, --Strength, 
	0.000, --On_Hand, 
	0.000, --Sales_Order_Reserved, 
	0.000, --Quote_Reserved, 
	0.000, --Job_Reserved, 
	0.000, --Min_Stock_Level, 
	NULL,--    Last_Sale_Date,
	1.000, --Service_Level, 
	0.000, --Max_Order_Qty, 
	0.000, --Min_Order_Qty, 
	0, --Slu_AW_YesNo_Assembly, 
	NULL, --Serial_Number, 
	0, --Show_Image, 
	NULL, --Image_File_Name, 
	0, --Slu_AW_YesNo_Edit_Price, 
	0, --Slu_AW_YesNo_Edit_Discount, 
	0.00, --Max_Discount_Perc, 
	0, --Slu_AW_YesNo_Max_Discount_Perc, 			
	NULL, --Memo, 
	NULL, --Keywords, 
	NULL, --PLU_Tab, 
	1, --Slu_AW_YesNo_Non_Stock_Item, 
	0, --GL_Purchases_ID,
	0, --GL_Sales_ID, 
	0, --GL_COS_ID, 
	GetDate(), --Date_Captured, 
	-1, --User_ID,
	1, --AW_User_Companies_ID, 
	1, --Slu_AW_Active_ID, 
	1, --Lup_AP_Purchase_Cateries_ID, 
	1, --Lup_AP_Markup_Groups_ID, 
	0, --Slu_AW_YesNo_Cost_Plus_Item, 
	1, --Lup_AP_AW_Weight_ID, 
	NULL, --Product_Weight, 
	1, --Slu_AW_YesNo_Levy_Item, 
	NULL, --Levy_AP_Product_ID, 
	2 --Levy_Weight_ID  
  )
  
  Set @AP_Products_ID = SCOPE_IDENTITY()
  
	IF NOT EXISTS
		(Select 1
		FROM AP_Products_Suppliers
		WHERE AO_Suppliers_ID = @AO_Suppliers_ID
		AND AP_Products_ID = @AP_Products_ID)
	BEGIN
		INSERT INTO 
				[AP_Products_Suppliers]
			   ([AP_Products_ID]
			   ,[AO_Suppliers_ID]
			   ,[Lead_Time]
			   ,[Trade_Disc_Perc]
			   ,[Trade_Disc_Date]
			   ,[Start_Date]
			   ,[AW_Trade_Discount_Formula_ID]
			   ,[AW_Rebate_Discount_Formula_ID]
			   ,[Date_Captured]
			   ,[User_ID]
			   ,[AW_User_Companies_ID]
			   ,[Slu_AW_Active_ID])
		 VALUES
			   (@AP_Products_ID--<AP_Products_ID, int,>
			   ,@AO_Suppliers_ID--<AO_Suppliers_ID, int,>
			   ,1--<Lead_Time, smallint,>
			   ,0.00--<Trade_Disc_Perc, decimal(5,2),>
			   ,'2012-10-01'--<Trade_Disc_Date, datetime,>
			   ,'2012-10-01'--<Start_Date, datetime,>
			   ,1--<AW_Trade_Discount_Formula_ID, smallint,>
			   ,1--<AW_Rebate_Discount_Formula_ID, smallint,>
			   ,GetDate()--<Date_Captured, datetime,>
			   ,-1--<User_ID, int,>
			   ,1--<AW_User_Companies_ID, int,>
			   ,1)--<Slu_AW_Active_ID, int,>)
	           
	END     
END	      
Go

IF NOT EXISTS
	(SELECT 1
	FROM AB_Accounts
	WHERE [Description] = 'Levies')
BEGIN	
	INSERT INTO [AB_Accounts]
           ([Description]
           ,[Account_Number]
           ,[Sys_AB_Account_Categories_ID]
           ,[Sys_AW_Tax_Codes_ID]
           ,[Lup_AB_Cost_Centers_ID]
           ,[AB_Account_Balance]
           ,[Opening_Balance]
           ,[Opening_Date]
           ,[Opening_Month]
           ,[Opening_Year]
           ,[AW_YesNo_Controllable_ID]
           ,[Date_Captured]
           ,[User_ID]
           ,[AW_User_Companies_ID]
           ,[Slu_AW_Active_ID]
           ,[Lup_AB_Account_Groups_ID]
           ,[Lup_AB_Account_Divisions_ID])
     VALUES
           ('Levies'--<Description, varchar(50),>
           ,NULL--<Account_Number, varchar(16),>
           ,14--<Sys_AB_Account_Categories_ID, int,>
           ,1--<Sys_AW_Tax_Codes_ID, tinyint,>
           ,1--<Lup_AB_Cost_Centers_ID, int,>
           ,0.00--<AB_Account_Balance, money,>
           ,0.00--<Opening_Balance, money,>
           ,'2012-10-01'--<Opening_Date, datetime,>
           ,0--<Opening_Month, tinyint,>
           ,0--<Opening_Year, int,>
           ,1--<AW_YesNo_Controllable_ID, tinyint,>
           ,GetDate()--<Date_Captured, datetime,>
           ,-1--<User_ID, int,>
           ,1--<AW_User_Companies_ID, int,>
           ,1--<Slu_AW_Active_ID, tinyint,>
           ,1--<Lup_AB_Account_Groups_ID, int,>
           ,1)--<Lup_AB_Account_Divisions_ID, int,>)
END
GO

--N15 Create user levy access control


--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='IsLevyController'
) 
BEGIN
  ALTER TABLE AW_Users ADD IsLevyController tinyint
            
  -------------------------------------------------------
  EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AW_Users].[IsLevyController]'
  -------------------------------------------------------
END
GO

UPDATE AW_Users
SET IsLevyController = 0
Go

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_Select_User_Rights]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_Select_User_Rights]
GO
/****** Object:  StoredProcedure [dbo].[sp_AW_Select_User_Rights]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_Select_User_Rights
--Purpose       :Select Rights of a User
--Parameters    :
--Date          :2008/04/30
--Authors       :TB
--MODS          :
--2004.4.8      :Added check validation on ACTIVE users only
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_Select_User_Rights]
	(
        @UserID int,
        @RightsID tinyint,
		@Setting tinyint OUTPUT
	)

AS

    SET @Setting = 0


    IF @RightsID = 1            --Is a Point-of-Sale Cashier
        BEGIN
        	SELECT @Setting = IsCashier
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 2            --Is a Point-of-Sale Supervisor
        BEGIN
        	SELECT @Setting = IsSupervisor
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 3            --Is a Database Administrator
        BEGIN
        	SELECT @Setting = IsDBAdmin
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 4            --Is a Customer Relations Manager
        BEGIN
        	SELECT @Setting = IsCRM
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 5            --Is a Credit Controller
        BEGIN
        	SELECT @Setting = IsController
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 6            --Is an Accountant
        BEGIN
        	SELECT @Setting = IsAccountant
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 7            --Is a Data Exporter
        BEGIN
        	SELECT @Setting = IsDataExporter
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

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

    ELSE
    IF @RightsID = 8            --Is a Procurement Supervisor
        BEGIN
        	SELECT @Setting = IsProcurementSupervisor
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

        	IF @Setting IS NULL 
                BEGIN	
            		SET @Setting = 0 
                END
        END
	IF @RightsID = 9            --Is a Product Levy Controller
        BEGIN
        	SELECT @Setting = IsLevyController
        	FROM AW_Users
            WHERE AW_Users_ID = @UserID AND
                  Slu_AW_Active_ID = 1

        	IF @Setting IS NULL 
                BEGIN	
            		SET @Setting = 0 
                END
        END
Go

--N16 Create user acces for levy product

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
/****** Object:  StoredProcedure [dbo].[sp_AW_Select_User_Lups]    Script Date: 09/17/2012 14:49:06 ******/
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     		

    END

SET NOCOUNT OFF
Go

--N17 sp_AW_Select_User_Catalog

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
/****** Object:  StoredProcedure [dbo].[sp_AW_Select_User_Catalog]    Script Date: 09/17/2012 14:49:06 ******/
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
-------------------------------------------------------------------------------

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

SET NOCOUNT OFF
GO

--N20 - sp_AP_Filter_Product_Update_Export

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Filter_Product_Update_Export]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Filter_Product_Update_Export]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Filter_Product_Update_Export]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Filter_Product_Update_Export
--Purpose       :Filters Product Update Products to Export
--Date          :2006/05/11
--Authors       :TB
--MODS          :
--2004.3.2      :11/09/06 - Added @LocationID input parameter and [Location] field
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :29/12/06 - Uncommented AP_Products_ID in SELECT to enable UPDATE RS
--              :           of sugFilterProducts in UI
--              :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--              :09/05/08 - Replaced [Max Disc] with [Min GP%] and [Apply Max] with [Apply Min%]
--              :09/05/08 - Added ALIAS to Profit Protector fields - unaliased caused wrong
--              :           values to be fetched !!!
--2004.4.0      :19/07/08 - Added NOT EDITABLE p.Last_Sale_Date AS [Last Sale] AS LAST COLUMN
--              :19/07/08 - Added @chkSortOrder input parameter to sort by [Last Sale]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--2004.5.7 RGL  :2012-11-01 - Added [Levy], [Weight Type], [Weight]
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AP_Filter_Product_Update_Export]
	(
    	@CompanyID int,
    	@ManufacturerID int = -1,
    	@TypeID int = -1,
    	@GroupID int = -1,
    	@DepartmentID int = -1,
    	@SupplierID int = -1,
    	@LocationID int = -1,
    	@PurchaseCatID int = -1,
    	@chkDateCaptured tinyint = -1,
    	@DateCaptured datetime,
    	@chkActiveOnly tinyint = -1,
    	@chkSortOrder tinyint = 0
	)
AS

SET NOCOUNT ON

	DECLARE @Filter varchar(2000),
            @sql varchar(8000)


	SET @Filter = ''
    SET @sql = ''


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


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


--> Fetch only Products from this Date Captured and later
    IF @chkDateCaptured = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
            ELSE
                SET @Filter = @Filter + '  AND p.Date_Captured >= ' + '''' + CONVERT(varchar(30), @DateCaptured) + '''' + ' '
        END


--> Fetch only ACTIVE Products
    IF @chkActiveOnly = 1
        BEGIN
    	    IF @Filter = ''
                SET @Filter = ' WHERE ' + ' p.Slu_AW_Active_ID = 1 '
            ELSE
                SET @Filter = @Filter + '  AND p.Slu_AW_Active_ID = 1 '
        END


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.AP_Products_ID AS [ID], '
    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Product Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '
    SET @sql = @sql + ' p.Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' p.SKU_Code AS [SKU Code], '
    SET @sql = @sql + ' p.Alternate_Code1 AS [Alt Code], '
    SET @sql = @sql + ' p.Alternate_Code2 AS [Bar Code], '
    SET @sql = @sql + ' p.Lup_AP_Product_Manufacturers_ID AS [Manufacturer], '
    SET @sql = @sql + ' p.Manufacturer_Code AS [Manuf Code], '
    SET @sql = @sql + ' p.Manufacturer_Description AS [Manuf Desc], '
    SET @sql = @sql + ' p.Default_Supplier_ID AS [Supplier], '
    SET @sql = @sql + ' p.Lup_AP_Product_Types_ID AS [Type], '
    SET @sql = @sql + ' p.Lup_AP_Product_Groups_ID AS [Group], '
    SET @sql = @sql + ' p.Lup_AP_Product_Departments_ID AS [Department], '
    SET @sql = @sql + ' p.Lup_AP_Product_Locations_ID AS [Location], '
--    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [Purchase Cat], '
    SET @sql = @sql + ' p.Lup_AP_Purchase_Categories_ID AS [PurchaseCat], '    
    SET @sql = @sql + ' p.Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' p.Average_Cost AS [Avg Cost], '
    SET @sql = @sql + ' p.Standard_Cost AS [Std Cost], '
    SET @sql = @sql + ' p.Price1_Effective_Date AS [Price1 Date], '
    SET @sql = @sql + ' p.Price1_Price1 AS [Price 1-1], '
    SET @sql = @sql + ' p.Price1_Price2 AS [Price 1-2], '
    SET @sql = @sql + ' p.Price2_Effective_Date AS [Price2 Date], '
    SET @sql = @sql + ' p.Price2_Price1 AS [Price 2-1], '
    SET @sql = @sql + ' p.Price2_Price2 AS [Price 2-2], '
    SET @sql = @sql + ' p.Pack_Volume AS [Volume], '
    SET @sql = @sql + ' p.Pack_Mass AS [Mass], '
    SET @sql = @sql + ' p.Slu_AW_Active_ID AS [Active], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Price AS [Edit Price], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
    SET @sql = @sql + ' p.Max_Discount_Perc AS [Min GP%], '
    SET @sql = @sql + ' p.Slu_AW_YesNo_Max_Discount_Perc AS [Apply Min%], '
    SET @sql = @sql + ' p.Last_Sale_Date AS [Last Sale], '
    SET @sql = @sql + ' p.Levy_AP_Product_ID AS [Levy], '
    SET @sql = @sql + ' p.Lup_AP_AW_Weight_ID AS [WeightType], '
    SET @sql = @sql + ' p.Product_Weight AS [Weight] '        
    
    SET @sql = @sql + ' FROM AP_Products p '
    SET @sql = @sql + @Filter

    IF @chkSortOrder = 0
        BEGIN
            SET @sql = @sql + ' ORDER BY p.[Description] '
        END

    IF @chkSortOrder = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY p.Last_Sale_Date DESC '
        END


	EXEC (@sql)

SET NOCOUNT OFF	
Go

--N21 - sp_AP_Enterprise_Product_Search_Lups

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Enterprise_Product_Search_Lups]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Enterprise_Product_Search_Lups]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Enterprise_Product_Search_Lups]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Enterprise_Product_Search_Lups
--Purpose       :Returns ONLY ACTIVE Lookups
--Date          :2006/10/14
--Authors       :TB
--MODS:         :
--2004.3.4      :27/02/07 - Added Option 10 Lup_AP_Purchase_Categories
--2004.3.8      :15/04/08 - Added Profit Protector lookup fields
--              :           [Edit Price], [Edit Disc], [Apply Max]
--2004.3.8      :09/05/08 - Replaced [Apply Max] with [Min GP%]
--2004.5.7 RGL  :2012-11-01 - Added 14 - Levy, 15 Weight
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Enterprise_Product_Search_Lups]
    (
    	@Option int
    )

AS

SET NOCOUNT ON

    --> Supplier
    	IF @Option = 1
    		SELECT AO_Suppliers_ID AS [ID],
    			Supplier_Name as [Description]
    		FROM AO_Suppliers
            WHERE Slu_AW_Active_ID = 1
            ORDER BY Supplier_Name

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

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

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

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

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

    --> Edit Price
    	ELSE 
    	IF @Option = 11
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Edit Disc
    	ELSE 
    	IF @Option = 12
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo

    --> Apply Min GP%
    	ELSE 
    	IF @Option = 13
    		SELECT Slu_AW_YesNo_ID AS [ID],
    			[Description] 
    		FROM Slu_AW_YesNo
    		
    --> Levy
    	ELSE 
    	IF @Option = 14
            SELECT AP_Products_ID AS [ID],
    		      [Description]
    		FROM AP_Products
    		WHERE Slu_AW_YesNo_Levy_Item = 1
            ORDER BY [Description] ASC

    --> Weight
    	ELSE             
    	IF @Option = 15
        	SELECT Lup_AP_AW_Weight_ID AS [ID], 
               [Description]
        	FROM Lup_AP_AW_Weight
        	WHERE Slu_AW_Active_ID = 1
            ORDER BY [Description]
            

SET NOCOUNT OFF
Go

--N22 - sp_AP_Select_Redundant_Products

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Redundant_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Redundant_Products]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Redundant_Products]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Redundant_Products
--Purpose       :SELECT Redundant UNUSED Products with ZERO STOCK in target DB
--Date          :2007/04/27
--Authors       :TB
--MODS:         :
--2004.5.7 RGL	: 2012-11-01 Exclude levy Products
-------------------------------------------------------------------------------

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

SET NOCOUNT ON


        SELECT a.AP_Products_ID AS [ProductID]
        FROM AP_Products a
            FULL OUTER JOIN AS_Transaction_Details b
                ON a.AP_Products_ID = b.AP_Products_ID
            FULL OUTER JOIN AO_GRV_Details c
                ON a.AP_Products_ID = c.AP_Products_ID
            FULL OUTER JOIN AO_Order_Details d
                ON a.AP_Products_ID = c.AP_Products_ID
        WHERE a.AW_User_Companies_ID = @CompanyID AND
              b.AP_Products_ID IS NULL AND
              c.AP_Products_ID IS NULL AND
              d.AP_Products_ID IS NULL AND
              a.On_Hand = 0 AND
              a.Slu_AW_YesNo_Levy_Item = 0
Go

--N23 - sp_AP_Insert_Product_Update

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

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

        @CompanyID int --37
	)

AS

SET NOCOUNT ON

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


    SET @RetCode = 0

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

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


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

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


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

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


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

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


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

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


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

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


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

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

    --> Get Levy ID
    SET @LevyID = NULL
    IF @Levy <> ''
        BEGIN
            SELECT TOP 1 @LevyID = AP_Products_ID
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @CompanyID AND
    			  Slu_AW_YesNo_Levy_Item = 1 AND
    			  [Description] = @Levy
        END
    

    --> Get Weight ID
    IF RTRIM(LTRIM(@WeightType)) = ''
        BEGIN
            SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
            FROM Lup_AP_AW_Weight
            WHERE AW_User_Companies_ID = @CompanyID AND
				  LTRIM(RTRIM([Description])) = @WeightType AND
                  Slu_AW_Active_ID = 1
        END
    ELSE
    IF @WeightType <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
						  LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_AW_Weight (Description, AW_User_Companies_ID) VALUES (@WeightType, @CompanyID)

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


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

    SELECT @ProductID = AP_Products_ID
    FROM AP_Products
    WHERE Product_Code = @ProductCode
      AND CONVERT(CHAR(19), Date_Captured) = CONVERT(CHAR(19), @DateCaptured)
      AND Slu_AW_Active_ID = 1


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


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

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

							@LevyID,
						    @WeightTypeID,
							@Weight
                        )
        
                    SET @RetCode = 2
                END
        END

RETURN @RetCode
Go

--N24 - Create Report LevyInventoryValuation

    IF NOT EXISTS
        (
            SELECT Sys_AW_Reports_ID
            FROM Sys_AW_Reports
            WHERE Report_No = '221' AND
                  Method_Name = 'Show_LevyInventoryValuation'
        ) 
        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',
                    '221',
                    'Levy Stock Valuation',
                    'Levy Stock Valuation',
                    'SpSProductReports',
                    'CInterface',
                    'Show_LevyInventoryValuation'
                )
        END
Go
--N25 - sp_AP_Select_Product_Update_Products

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Select_Product_Update_Products]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Select_Product_Update_Products]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Select_Product_Update_Products]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--!!!!! NB NB NB: DO NOT CHANGE FIELD ALIASES OR POSITIONS !!!!!

-------------------------------------------------------------------------------
--Description   :sp_AP_Select_Product_Update_Products
--Purpose       :Select Products for Product Updates
--Date          :2006/06/02
--Authors       :TB
--MODS          :
--2004.3.2      :11/09/06 - Added [Location] field
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :27/02/07 - Added [Purchase Cat] field
--2004.3.8      :15/04/08 - Added Profit Protector fields [Edit Price], [Edit Disc]
--              :           [Max Disc], [Apply Max]
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
-------------------------------------------------------------------------------

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

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' [Description] AS [Description], '
    SET @sql = @sql + ' Product_Code AS [Product Code], '
    SET @sql = @sql + ' Pack_Size AS [Size], '
    SET @sql = @sql + ' Date_Captured AS [Date Captured], '
    SET @sql = @sql + ' SKU_Code AS [SKU Code], '
    SET @sql = @sql + ' Alternate_Code1 AS [Alt Code], '
    SET @sql = @sql + ' Alternate_Code2 AS [Bar Code], '
    SET @sql = @sql + ' Lup_AP_Product_Manufacturers_ID AS [Manufacturer], '
    SET @sql = @sql + ' Manufacturer_Code AS [Manuf Code], '
    SET @sql = @sql + ' Manufacturer_Description AS [Manuf Desc], '
    SET @sql = @sql + ' Default_Supplier_ID AS [Supplier], '
    SET @sql = @sql + ' Lup_AP_Product_Types_ID AS [Type], '
    SET @sql = @sql + ' Lup_AP_Product_Groups_ID AS [Group], '
    SET @sql = @sql + ' Lup_AP_Product_Departments_ID AS [Department], '
    SET @sql = @sql + ' Lup_AP_Product_Locations_ID AS [Location], '
    SET @sql = @sql + ' Lup_AP_Purchase_Categories_ID AS [Purchase Cat], '
    SET @sql = @sql + ' Last_Cost AS [Last Cost], '
    SET @sql = @sql + ' Average_Cost AS [Avg Cost], '
    SET @sql = @sql + ' Standard_Cost AS [Std Cost], '
    SET @sql = @sql + ' Price1_Effective_Date AS [Price1 Date], '
    SET @sql = @sql + ' Price1_Price1 AS [Price 1-1], '
    SET @sql = @sql + ' Price1_Price2 AS [Price 1-2], '
    SET @sql = @sql + ' Price2_Effective_Date AS [Price2 Date], '
    SET @sql = @sql + ' Price2_Price1 AS [Price 2-1], '
    SET @sql = @sql + ' Price2_Price2 AS [Price 2-2], '
    SET @sql = @sql + ' Pack_Volume AS [Volume], '
    SET @sql = @sql + ' Pack_Mass AS [Mass], '
    SET @sql = @sql + ' Slu_AW_Active_ID AS [Active], '
    SET @sql = @sql + ' Slu_AW_YesNo_Edit_Price AS [Edit Price], '
    SET @sql = @sql + ' Slu_AW_YesNo_Edit_Discount AS [Edit Disc], '
    SET @sql = @sql + ' Max_Discount_Perc AS [Max Disc], '
    SET @sql = @sql + ' Slu_AW_YesNo_Max_Discount_Perc AS [Apply Max], '
    SET @sql = @sql + ' Levy_AP_Product_ID AS [Levy], '
    SET @sql = @sql + ' Lup_AP_AW_Weight_ID AS [WeightType], '
    SET @sql = @sql + ' Product_Weight AS [Weight] '            
    SET @sql = @sql + ' FROM AP_Products '
    SET @sql = @sql + ' WHERE AW_User_Companies_ID = ' + CONVERT(varchar(20), @CompanyID) + ' '
    SET @sql = @sql + '   AND Date_Captured > ' + '''' + CONVERT(varchar(30), DATEADD(year, 1, getdate())) + ''''
    SET @sql = @sql + ' ORDER BY [Description] '

SET NOCOUNT OFF

EXEC (@sql)
Go

--N26 - sp_AP_Insert_Product_Update

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Get_Product_Lookup_ID]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Get_Product_Lookup_ID]
GO
/****** Object:  StoredProcedure [dbo].[sp_AP_Get_Product_Lookup_ID]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AP_Insert_Product_Update
--Purpose       :INSERT Enterprise Stock
--Date          :2006/06/01
--Authors       :TB
--MODS:         :
--2004.3.2      :11/09/06 - Added @LocationID input parameter and [Location] field
--              :15/09/06 - Added SELECT only ACTIVE lookups (Slu_AW_Active_ID = 1)
--              :30/09/06 - Added [GL Purchases], [GL Sales], [GL COS] fields
--2004.3.4      :27/02/07 - Added input parameters for Lup_AP_Purchase_Categories
--2004.5.0      :10/03/11 - Removed [GL Purchases], [GL Sales], [GL COS] fields
--              :10/03/11 - Replaced get top 1 LookupID if Lookup does not exist
--              :           with INSERT LOOKUP if NOT EXISTS LOOKUP
--2004.5.2      :11/07/11 - Fixed @Supplier field length to new size 40 !!!!
--2004.5.7 RGL  :2012-11-01 - Added Levy and WeightLookup
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Get_Product_Lookup_ID]
	(
        @CompanyID int,
        @Manuf varchar(30),
        @Supplier varchar(40),
        @Type varchar(50),
        @Group varchar(50),
        @Dept varchar(50),
        @Location varchar(50),
        @PurchaseCat varchar(50),
        @Levy varchar(50),
        @WeightType varchar(50),
                
        @ManufID int OUTPUT,
        @SupplierID int OUTPUT,
        @TypeID int OUTPUT,
        @GroupID smallint OUTPUT,
        @DeptID int OUTPUT,
        @LocationID int OUTPUT,
        @PurchaseCatID int OUTPUT,
        @LevyID int OUTPUT,
        @WeightTypeID smallint OUTPUT        
	)

AS

SET NOCOUNT ON

	DECLARE @RetCode int


    SET @RetCode = 0

	SET @Manuf = RTRIM(LTRIM(ISNULL(@Manuf,'')))
	SET @Supplier = RTRIM(LTRIM(ISNULL(@Supplier,'')))
	SET @Type = RTRIM(LTRIM(ISNULL(@Type,'')))
	SET @Group = RTRIM(LTRIM(ISNULL(@Group,'')))
	SET @Dept = RTRIM(LTRIM(ISNULL(@Dept,'')))
	SET @Location = RTRIM(LTRIM(ISNULL(@Location,'')))
	SET @PurchaseCat = RTRIM(LTRIM(ISNULL(@PurchaseCat,'')))
	SET @WeightType = RTRIM(LTRIM(ISNULL(@WeightType,'')))
	SET @Levy = RTRIM(LTRIM(ISNULL(@Levy,'')))

    --> Get Manufacturer ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Product_Manufacturers_ID
            FROM Lup_AP_Product_Manufacturers
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Manuf AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Product_Manufacturers (Description, AW_User_Companies_ID) VALUES (@Manuf, @CompanyID)

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


    --> Get Supplier ID
    IF NOT EXISTS
        (
            SELECT AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Supplier_Name = @Supplier AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT AO_Suppliers (Supplier_Name, AW_User_Companies_ID) VALUES (@Supplier, @CompanyID)

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


    --> Get Product Type ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Product_Types_ID
            FROM Lup_AP_Product_Types
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Type AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Product_Types (Description, AW_User_Companies_ID) VALUES (@Type, @CompanyID)

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


    --> Get Product Group ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Product_Groups_ID
            FROM Lup_AP_Product_Groups
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Group AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Product_Groups (Description, AW_User_Companies_ID) VALUES (@Group, @CompanyID)

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


    --> Get Product Department ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Dept AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Product_Departments (Description, AW_User_Companies_ID) VALUES (@Dept, @CompanyID)

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


    --> Get Product Location ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Product_Locations_ID
            FROM Lup_AP_Product_Locations
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Location AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Product_Locations (Description, AW_User_Companies_ID) VALUES (@Location, @CompanyID)

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


    --> Get Purchase Category ID
    IF NOT EXISTS
        (
            SELECT Lup_AP_Purchase_Categories_ID
            FROM Lup_AP_Purchase_Categories
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @PurchaseCat AND
                  Slu_AW_Active_ID = 1
        )
        BEGIN
            INSERT Lup_AP_Purchase_Categories (Description, AW_User_Companies_ID) VALUES (@PurchaseCat, @CompanyID)

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

    --> Get Levy ID
    SET @LevyID = 0
    IF @Levy <> ''
        BEGIN
            SELECT TOP 1 @LevyID = AP_Products_ID
    		FROM AP_Products
    		WHERE AW_User_Companies_ID = @CompanyID AND
    			  Slu_AW_YesNo_Levy_Item = 1 AND
    			  [Description] = @Levy
        END
    

    --> Get Weight ID
    IF RTRIM(LTRIM(@WeightType)) = ''
        BEGIN
            SELECT TOP 1 @WeightTypeID = Lup_AP_AW_Weight_ID
            FROM Lup_AP_AW_Weight
            WHERE AW_User_Companies_ID = @CompanyID AND
				  LTRIM(RTRIM([Description])) = @WeightType AND
                  Slu_AW_Active_ID = 1
        END
    ELSE
    IF @WeightType <> ''
        BEGIN
            IF NOT EXISTS
                (
                    SELECT Lup_AP_AW_Weight_ID
                    FROM Lup_AP_AW_Weight
                    WHERE AW_User_Companies_ID = @CompanyID AND
						  LTRIM(RTRIM([Description])) = @WeightType AND
                          Slu_AW_Active_ID = 1
                )
                BEGIN
                    INSERT Lup_AP_AW_Weight (Description, AW_User_Companies_ID) VALUES (@WeightType, @CompanyID)

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

    SET @RetCode = 1

    RETURN @RetCode
GO

--N27 - sp_RPT_AP_Levy_Inventory_Valuation

IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AP_Levy_Inventory_Valuation]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AP_Levy_Inventory_Valuation]
GO
/****** Object:  StoredProcedure [dbo].[sp_RPT_AP_Levy_Inventory_Valuation]    Script Date: 09/17/2012 14:49:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AP_Levy_Inventory_Valuation
--Purpose       :Selects ALL Products with Sales in selected SORT ORDER DESC
--Date          :2004/08/24
--Authors       :TB
--MODS:         :29/09/04 - Added [LastUnitCost] and [AvgUnitCost] fields
--              :10/06/05 - Added [StdUnitCost] and [Std Cost] fields and @NonStock
--              :           input parameter replaced Std GP% with Avg GP%
--2004.3.2      :19/09/06 - Added Pack_Size AS [Size] field for Enterprise Valuation
--              :21/09/06 - Added @AssignStd to Assign Last Cost if Std. Cost zero
--2004.4.2      :09/11/08 - Added Assign Secondary Costing method if Standard Cost zero
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_RPT_AP_Levy_Inventory_Valuation]
    (
        @ValuationID int,
        @Option varchar(20),
        @OnHandOnly tinyint,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)

    SET @sql = ' SELECT h.AW_User_Companies_ID as [CompanyID], '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID as [HeaderID], ' +
            ' o.[Supplier_Name] as [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID as [HeaderID], ' +
            ' o.[Description] as [Filter], '

    SET @sql = @sql + ' p.[Description] AS [Description], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' w.Description AS [WeightType], '
    SET @sql = @sql + ' p.Product_Weight AS [ProductWeight], '        
    SET @sql = @sql + ' h.Qty AS [Qty], '
    SET @sql = @sql + ' (Select CONVERT(money, (x.Price1_Price1)) From AP_Products x Where x.AP_Products_ID = p.Levy_AP_Product_ID) AS [Selling], '    
    SET @sql = @sql + ' (h.Qty * ISNull(p.Product_Weight,0)) AS [TotalWeight], '    
    SET @sql = @sql + ' ( (h.Qty * ISNull(p.Product_Weight,0)) * (Select CONVERT(money, (x.Price1_Price1)) From AP_Products x Where x.AP_Products_ID = p.Levy_AP_Product_ID) ) AS [LevyAmount] '    
   
    SET @sql = @sql + ' FROM AP_Products_History h '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON h.AP_Products_ID = p.AP_Products_ID '

    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '


    SET @sql = @sql +
        '    LEFT JOIN Lup_AP_AW_Weight w ' +
        '        ON p.Lup_AP_AW_Weight_ID = w.Lup_AP_AW_Weight_ID '


    SET @sql = @sql +
        ' WHERE h.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '       h.AW_Period_Procedures_ID = ' + CONVERT(varchar(10), @ValuationID) + ' '


    IF @OnHandOnly = 1
        BEGIN
            SET @sql = @sql + '   AND h.Qty <> 0 '
        END

	SET @sql = @sql + '   AND p.Levy_AP_Product_ID > 0 '


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


EXEC (@sql)

GO

--N30 Update AP_Products GL's

IF Exists
( SELECT 1
  FROM AP_Products
  WHERE Product_Code = 'RTW-Levy' AND
		GL_Purchases_ID = 0 AND
		GL_Sales_ID = 0 AND
		GL_COS_ID = 0)
BEGIN
	Declare 
		@GL_Purchases_ID Integer,
		@GL_Sales_ID Integer,
		@GL_COS_ID Integer	

	SELECT @GL_Purchases_ID = AB_Accounts_ID
	FROM AB_Control_Accounts
	WHERE Control_Number = 601 -- Purchases

	SELECT @GL_Sales_ID = AB_Accounts_ID
	FROM AB_Control_Accounts
	WHERE Control_Number = 102 --Sales Control

	SELECT @GL_COS_ID = AB_Accounts_ID
	FROM AB_Control_Accounts
	WHERE Control_Number = 106 --Cost Of Sales Control                 
    
    UPDATE AP_Products
	SET	GL_Purchases_ID = @GL_Purchases_ID,
		GL_Sales_ID = @GL_Sales_ID,
		GL_COS_ID = @GL_COS_ID
	WHERE Product_Code = 'RTW-Levy' AND
		GL_Purchases_ID = 0 AND
		GL_Sales_ID = 0 AND
		GL_COS_ID = 0                    			

END		
Go

---------------------------------------------------------------------------------
-- END Levy Implementation
---------------------------------------------------------------------------------






---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------
IF NOT EXISTS
    (
        SELECT AA_Release_ID
        FROM AA_Release
        WHERE Release = '2004.5.7'
    )
    BEGIN
        INSERT AA_Release
            (
                Release,
                Updated_by			  
            )
        VALUES
            (
                '2004.5.7',
                'Upgrade CD'
            )
    END
ELSE
    BEGIN
        UPDATE AA_Release
        SET Updated_by = 'Upgrade CD',
            Date_Updated = getdate()
        WHERE Release = '2004.5.7'
    END
Go    